move paradiseo/eo to deprecated/ before merge with eodev

This commit is contained in:
Johann Dreo 2012-10-05 15:12:12 +02:00
commit 0c5120f675
717 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,116 @@
###############################################################################
##
## CMakeLists file for eo/test
##
###############################################################################
######################################################################################
### 1) Include the sources
######################################################################################
INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src)
INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/contrib)
INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/contrib/MGE)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
######################################################################################
### 2) Specify where CMake can find the libraries
######################################################################################
LINK_DIRECTORIES(${EO_BINARY_DIR}/lib)
######################################################################################
### 3) Define your targets and link the librairies
######################################################################################
SET (TEST_LIST
t-eofitness
t-eoRandom
t-eobin
t-eoVirus
t-MGE
t-MGE1bit
t-MGE-control
t-eoStateAndParser
t-eoCheckpointing
t-eoSSGA
t-eoExternalEO
t-eoSymreg
t-eo
t-eoReplacement
t-eoSelect
t-eoGenOp
t-eoGA
t-eoReal
t-eoVector
t-eoESAll
t-eoPBIL
t-eoFitnessAssembled
t-eoFitnessAssembledEA
t-eoRoulette
t-eoSharing
t-eoCMAES
t-eoSecondsElapsedContinue
t-eoRNG
t-eoEasyPSO
t-eoInt
t-eoInitPermutation
t-eoSwapMutation
t-eoShiftMutation
t-eoTwoOptMutation
t-eoRingTopology
t-eoSyncEasyPSO
t-eoOrderXover
t-eoExtendedVelocity
t-eoLogger
#t-eoIQRStat # Temporary by-passed in order to test coverage
t-eoParallel
#t-openmp # does not work anymore since functions used in this test were removed from EO
#t-eoDualFitness
t-eoParser
)
FOREACH (test ${TEST_LIST})
SET ("T_${test}_SOURCES" "${test}.cpp")
ENDFOREACH (test)
IF(ENABLE_MINIMAL_CMAKE_TESTING)
SET (MIN_TEST_LIST t-eoEasyPSO)
FOREACH (mintest ${MIN_TEST_LIST})
SET ("T_${mintest}_SOURCES" "${mintest}.cpp")
ADD_EXECUTABLE(${mintest} ${T_${mintest}_SOURCES})
ADD_TEST(${mintest} ${mintest})
TARGET_LINK_LIBRARIES(${mintest} ga es cma eoutils eo)
ENDFOREACH (mintest)
ELSEIF(ENABLE_CMAKE_TESTING)
FOREACH (test ${TEST_LIST})
ADD_EXECUTABLE(${test} ${T_${test}_SOURCES})
ADD_TEST(${test} ${test})
TARGET_LINK_LIBRARIES(${test} ga es cma eoutils eo)
INSTALL(TARGETS ${test} RUNTIME DESTINATION local/share${INSTALL_SUB_DIR}/eo/test COMPONENT test)
ENDFOREACH (test)
SET(RESOURCES
boxplot.py
boxplot_to_png.py
boxplot_to_pdf.py
t-openmp.py
)
FOREACH(file ${RESOURCES})
EXECUTE_PROCESS(
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${CMAKE_CURRENT_SOURCE_DIR}/${file}
${CMAKE_CURRENT_BINARY_DIR}/${file}
)
ENDFOREACH(file)
ENDIF(ENABLE_MINIMAL_CMAKE_TESTING)
######################################################################################

View file

@ -0,0 +1,36 @@
2006-12-04 Jochen Kpper <jochen@fhi-berlin.mpg.de>
* Makefile.am: Add t-eoRNG
* t-eoRNG.cpp: Start test for random number generator.
2006-12-02 Jochen Kpper <jochen@fhi-berlin.mpg.de>
* t-MGE1bit.cpp: Change float to double.
* t-eoGenOp.cpp (init): Do not add std::ends to end of string, as this
results in escape-codes (^@) to be printed at runtime and is not
necessary anyway.
* test/t-eoSymreg.cpp (SymregNode::operator()): Initialize r1 and r2 to
avoid compiler warnings.
2006-07-02 Thomas Legrand <thomas.legrand@inria.fr>
* test/t-eoEasyPSO.cpp: added PSO test
* test/Makefile.am: added PSO test
2006-02-27 Thomas Legrand <thomas.legrand@inria.fr>
* test/t-eoSyncEasyPSO.cpp: added synchronous PSO test
* test/t-eoEasyPSO.cpp: customized PSO test (initialization)
* test/Makefile.am: added synchronous PSO test
* Local Variables:
* coding: iso-8859-1
* mode: flyspell
* fill-column: 80
* End:

View file

@ -0,0 +1,60 @@
/*
RoyalRoad.h
-- Implementation of the Royal Road function for any length and block size
(c) GeNeura Team 2001, Marc Schoenauer 2000
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
CVS Info: $Date: 2001-06-21 12:03:17 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/test/RoyalRoad.h,v 1.3 2001-06-21 12:03:17 jmerelo Exp $ $Author: jmerelo $
*/
#ifndef RoyalRoad_h
#define RoyalRoad_h
template<class EOT>
class RoyalRoad: public eoEvalFunc<EOT> {
public:
typedef typename EOT::Fitness FitT;
/// Ctor: takes a length, and divides that length in equal parts
RoyalRoad( unsigned _div ): eoEvalFunc<EOT >(), div( _div ) {};
// Applies the function
virtual void operator() ( EOT & _eo ) {
FitT fitness = 0;
if (_eo.invalid()) {
for ( unsigned i = 0; i < _eo.size()/div; i ++ ) {
bool block = true;
for ( unsigned j = 0; j < div; j ++ ) {
block &= _eo[i*div+j];
}
if (block) {
fitness += div;
}
}
_eo.fitness( fitness );
}
};
private:
unsigned div;
};
#endif

View file

@ -0,0 +1,16 @@
#include <algorithm>
//-----------------------------------------------------------------------------
/** Just the simple function that takes binary value of a chromosome and sets
the fitnes.
@param _chrom A binary chromosome
*/
template <class Chrom> double binary_value(const Chrom& _chrom)
{
double sum = 0.0;
for (unsigned i=0; i<_chrom.size(); i++)
sum += _chrom[i];
return sum;
}

15
deprecated/eo/test/boxplot.py Executable file
View file

@ -0,0 +1,15 @@
#!/usr/bin/env python
import pylab
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'Usage: boxplot.py [Results files, ...]'
sys.exit()
for i in range(1, len(sys.argv)):
pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] )
pylab.xlabel('iterations')
pylab.show()

View file

@ -0,0 +1,15 @@
#!/usr/bin/env python
import pylab
import sys
if __name__ == '__main__':
if len(sys.argv) < 3:
print 'Usage: boxplot_to_pdf.py [Results files, ...] [output file in .pdf]'
sys.exit()
for i in range(1, len(sys.argv) - 1):
pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] )
pylab.xlabel('iterations')
pylab.savefig( sys.argv[ len(sys.argv) - 1 ], format='pdf', transparent=True )

View file

@ -0,0 +1,15 @@
#!/usr/bin/env python
import pylab
import sys
if __name__ == '__main__':
if len(sys.argv) < 3:
print 'Usage: boxplot_to_png.py [Results files, ...] [output file in .png]'
sys.exit()
for i in range(1, len(sys.argv) - 1):
pylab.boxplot( [ [ float(value) for value in line.split() ] for line in open( sys.argv[i] ).readlines() ] )
pylab.xlabel('iterations')
pylab.savefig( sys.argv[ len(sys.argv) - 1 ], format='png', transparent=True, papertype='a0' )

View file

@ -0,0 +1,431 @@
#include <map> // for pair
#include <iostream>
#include <stdexcept>
#include <vector>
#include <algorithm>
#include <math.h> // for exp
using namespace std;
/* fitness_traits.h */
// default traits: defaults to a double that needs to be maximized
template <class T = double>
struct fitness_traits
{
// Needs mapping can be used to figure out whether you need to do fitness scaling (or not)
const static bool needs_mapping = false;
// storage_type: what to store next to the genotype
typedef T storage_type;
// performance_type: what the eoEvalFunc calculates
typedef T performance_type;
// worth_type: what the scaling function does
typedef T worth_type;
// access_performance: how to get from what is stored to a mutable performance
static performance_type& access_performance(storage_type& a) { return a; }
// access_worth: how to get from what is stored to a mutable worth
static worth_type& access_worth(storage_type& a) { return a; }
// get_performance: from storage_type to a performance figure
static performance_type get_performance(storage_type a) { return a; }
// get_worth: from storage_type to a worth figure
static worth_type get_worth(storage_type a) { return a; }
// get the fitness out of the individual
template <class EOT>
static worth_type get_fitness(const EOT& _eo) { return _eo.performance(); }
// compare the two individuals
template <class EOT>
static bool is_better(const EOT& _eo1, const EOT& _eo2)
{
return _eo1.performance() > _eo2.performance();
}
};
struct minimization {};
struct maximization {};
struct fitness_traits<minimization> : public fitness_traits<double>
{
// for minimization, invert the is_better
template <class EOT>
static bool is_better(const EOT& _eo1, const EOT& _eo2)
{
return _eo1.performance() < _eo2.performance();
}
};
// for maximization, just take the default behaviour
struct fitness_traits<maximization> : public fitness_traits<double> {};
// forward declaration
//template <class EOT> class eoPop;
//template <class Fitness, class Traits> class EO;
// unfortunately, partial template specialization is not approved by Microsoft (though ANSI says it's ok)
// Probably need some macro-magic to make this work (MicroSoft == MacroHard)
// A pair class: first == performance, second == worth, redefine all types, data and functions
template <class Performance, class Worth>
struct fitness_traits< pair<Performance, Worth> >
{
typedef pair<Performance, Worth> storage_type;
typedef Performance performance_type;
typedef Worth worth_type;
const static bool needs_mapping = true;
static performance_type& access_performance(storage_type& a) { return a.first; }
static worth_type& access_worth(storage_type& a) { return a.second; }
static performance_type get_performance(const storage_type& a) { return a.first; }
static worth_type get_worth(const storage_type& a) { return a.second; }
// This function calls _eo.worth() which in turn checks the fitness flag and calls get_worth above
// The compiler should be able to inline all these calls and come up with a very compact solution
template <class EOT>
static worth_type get_fitness(const EOT& _eo) { return _eo.worth(); }
template <class EOT>
static bool is_better(const EOT& _eo1, const EOT& _eo2)
{
return _eo1.worth() > _eo2.worth();
}
};
/* end fitness_traits.h */
/* EO.h
The Fitness template argument is there for backward compatibility reasons
*/
template <class Fitness, class Traits = fitness_traits<Fitness> >
class EO
{
public :
typedef Traits fitness_traits;
typedef typename Traits::storage_type storage_type;
typedef typename Traits::performance_type performance_type;
typedef typename Traits::worth_type worth_type;
EO() : valid_performance(false), valid_worth(false), rep_fitness() {}
// for backwards compatibility
void fitness(performance_type perf)
{
performance(perf);
}
void performance(performance_type perf)
{
valid_performance = true;
Traits::access_performance(rep_fitness) = perf;
}
performance_type performance(void) const
{
if(!valid_performance) throw runtime_error("no performance");
return Traits::get_performance(rep_fitness);
}
void worth(worth_type worth)
{
valid_worth = true;
Traits::access_worth(rep_fitness) = worth;
}
worth_type worth(void) const
{
if(!valid_worth) throw runtime_error("no worth");
if(!Traits::needs_mapping) throw runtime_error("no mapping");
return Traits::get_worth(rep_fitness);
}
worth_type fitness(void) const
{
return Traits::get_fitness(*this);
}
void invalidate(void)
{
valid_performance = false;
valid_worth = false;
}
void invalidate_worth(void)
{
valid_worth = false;
}
bool operator<(const EO<Fitness, Traits>& other) const
{
return !Traits::is_better(other, *this);
}
bool operator>(const EO<Fitness, Traits>& other) const
{
return Traits::is_better(other, *this);
}
private :
bool valid_performance;
bool valid_worth;
storage_type rep_fitness;
};
/* end EO.h */
/* eoPerf2Worth.h */
// get the name known
template <class EOT> class eoPop;
template <class EOT>
void exponential_scaling(eoPop<EOT>& _pop)
{
for (unsigned i = 0; i < _pop.size(); ++i)
{ // change minimimization into maximization
_pop[i].worth(exp(-_pop[i].performance()));
}
}
template <class EOT>
class eoPerf2Worth /* : public eoUF<eoPop<EOT>&, void> */
{
public :
virtual void operator()(eoPop<EOT>& _pop)
{
return exponential_scaling(_pop);
}
};
/* end eoPerf2Worth.h */
/* eoPop.h */
template <class EOT>
class eoPop : public vector<EOT>
{
public :
typedef typename EOT::fitness_traits fitness_traits;
eoPop(void) : p2w(0) {}
void sort()
{
scale(); // get the worths up to date
std::sort(begin(), end(), greater<EOT>());
}
void scale()
{
if (p2w)
{
if (!fitness_traits::needs_mapping)
{
throw runtime_error("eoPop: no scaling needed, yet a scaling function is defined");
}
(*p2w)(*this);
}
else if (fitness_traits::needs_mapping)
{
throw runtime_error("eoPop: no scaling function attached to the population, while one was certainly called for");
}
}
void setPerf2Worth(eoPerf2Worth<EOT>& _p2w)
{
p2w = &_p2w;
}
void setPerf2Worth(eoPerf2Worth<EOT>* _p2w)
{
p2w = _p2w;
}
eoPerf2Worth<EOT>* getPerf2Worth() { return p2w; }
void swap(eoPop<EOT>& other)
{
vector<EOT>::swap(other);
eoPerf2Worth<EOT>* tmp = p2w;
p2w = other.p2w;
other.p2w = tmp;
}
private :
// a pointer as it can be emtpy
eoPerf2Worth<EOT>* p2w;
};
// need this one to be able to swap the members as well...
template <class EOT>
void swap(eoPop<EOT>& _p1, eoPop<EOT>& _p2)
{
_p1.swap(_p2);
}
/* end eoPop.h */
/* main and test */
template <class EOT>
void algo(eoPop<EOT>& _pop)
{
eoPop<EOT> offspring; // how to get the scaling info into this guy??
offspring.setPerf2Worth(_pop.getPerf2Worth()); // like this!
std::copy(_pop.begin(), _pop.end(), back_inserter(offspring));
offspring.sort(); // should call scale
swap(_pop, offspring);
}
void minimization_test()
{
typedef EO<minimization> eo_type;
eo_type eo1;
eo_type eo2;
eo1.performance(1.0);
eo2.performance(2.0);
std::cout << "With minimizing fitness" << std::endl;
std::cout << eo1.fitness() << " < " << eo2.fitness() << " returns " << (eo1 < eo2) << std::endl;
std::cout << eo2.fitness() << " < " << eo1.fitness() << " returns " << (eo2 < eo1) << std::endl;
}
void the_main()
{
typedef EO<double> simple_eo;
typedef EO<pair<double, double> > scaled_eo;
simple_eo eo1;
simple_eo eo3;
/* First test some simple comparisons */
eo1.fitness(10); // could also use performance()
eo3.fitness(5);
std::cout << eo1.fitness() << std::endl;
std::cout << eo3.fitness() << std::endl;
std::cout << "eo1 < eo3 = " << (eo1 < eo3) << std::endl;
scaled_eo eo2;
scaled_eo eo4;
eo2.performance(10);
eo4.performance(8);
/* Now test if the worth gets accessed and if the flag protects it */
try
{
std::cout << eo2.fitness() << std::endl;
std::cout << "did not throw" << std::endl;
assert(false); // should throw
}
catch(std::exception& e)
{
std::cout << "Fitness threw exception, as it should" << std::endl;
std::cout << e.what() << std::endl;
}
/* Set the worth and all is well (this is normally done by some perf2worth functor */
eo2.worth(3);
eo4.worth(5);
std::cout << "with maximization " << std::endl;
std::cout << eo2.fitness() << std::endl;
std::cout << eo4.fitness() << std::endl;
std::cout << eo2.fitness() << " < " << eo4.fitness() << " returns " << (eo2 < eo4) << std::endl;
/* Test the minimization of fitness */
minimization_test();
/* Populations */
// test pop without scaling, should have no overhead save for a single empty pointer in pop
eoPop<simple_eo> pop0;
pop0.resize(1);
pop0[0].fitness(1);
algo(pop0);
std::cout << pop0[0].fitness() << std::endl;
assert(pop0[0].fitness() == 1);
/* test pop with scaling */
eoPerf2Worth<scaled_eo> perf2worth;
eoPop<scaled_eo> pop1;
pop1.resize(1);
pop1[0].fitness(1.0); // emulate evaluation
// at this point getting the fitness should throw
try
{
std::cout << pop1[0].fitness() << std::endl;
std::cout << "did not throw" << std::endl;
assert(false); // should throw
}
catch(std::exception& e)
{
std::cout << "Fitness threw exception, as it should" << std::endl;
std::cout << e.what() << std::endl;
}
// at this point trying to scale should throw
try
{
algo(pop1); // should complain that it cannot scale
assert(false); // so it would never get here
}
catch(std::exception& e)
{ // but rather ends here
std::cout << e.what() << std::endl;
}
// ok, now set the scaling
pop1.setPerf2Worth(perf2worth);
algo(pop1);
std::cout << "the fitness has been transformed from " << pop1[0].performance() << " to exp(-1) = " << pop1[0].fitness() << std::endl;
}
int main()
{
try
{
the_main();
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}

View file

@ -0,0 +1,16 @@
#include <vector>
//-----------------------------------------------------------------------------
/** Just a simple function that takes an eoEsBase<double> and sets the fitnes
to sphere
@param _ind vector<double>
*/
double real_value(const std::vector<double>& _ind)
{
double sum = 0;
for (unsigned i = 0; i < _ind.size(); i++)
sum += _ind[i] * _ind[i];
return sum/_ind.size();
}

9
deprecated/eo/test/run_tests Executable file
View file

@ -0,0 +1,9 @@
#!/bin/sh
echo "Testing -h"
./t-eoCheckpointing -h
echo "Finished"
#TODO test if an error occured
echo "Ok"

View file

@ -0,0 +1,104 @@
//-----------------------------------------------------------------------------
// t-eoMGE.cpp
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef __GNUG__
// to avoid long name warnings
#pragma warning(disable:4786)
#endif // __GNUG__
#include "eo"
#include "ga/eoBitOp.h"
#include "RoyalRoad.h"
// Viri
#include "VirusOp.h"
#include "eoVirus.h"
#include "eoInitVirus.h"
//-----------------------------------------------------------------------------
typedef eoVirus<float> Chrom;
//-----------------------------------------------------------------------------
int main()
{
const unsigned POP_SIZE = 10, CHROM_SIZE = 12;
unsigned i;
eoBooleanGenerator gen;
// the populations:
eoPop<Chrom> pop;
// Evaluation
RoyalRoad<Chrom> rr( 8 );
eoEvalFuncCounter<Chrom> eval( rr );
eoInitVirus<float> random(CHROM_SIZE, gen);
for (i = 0; i < POP_SIZE; ++i) {
Chrom chrom;
random(chrom);
eval(chrom);
pop.push_back(chrom);
}
std::cout << "population:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
// selection
eoStochTournamentSelect<Chrom> lottery(0.9 );
// breeder
eoOneBitFlip<Chrom> vm;
eoUBitXover<Chrom> xover;
eoProportionalOp<Chrom> propSel;
eoGeneralBreeder<Chrom> breeder( lottery, propSel );
propSel.add(vm, 0.2);
propSel.add(xover, 0.8);
// Replace a single one
eoCommaReplacement<Chrom> replace;
// Terminators
eoGenContinue<Chrom> continuator1(10);
eoFitContinue<Chrom> continuator2(CHROM_SIZE);
eoCombinedContinue<Chrom> continuator(continuator1, continuator2);
eoCheckPoint<Chrom> checkpoint(continuator);
eoStdoutMonitor monitor;
checkpoint.add(monitor);
eoSecondMomentStats<Chrom> stats;
eoPopStat<Chrom> dumper( 10 );
monitor.add(stats);
checkpoint.add(dumper);
checkpoint.add(stats);
// GA generation
eoEasyEA<Chrom> ea(checkpoint, eval, breeder, replace );
// evolution
try
{
ea(pop);
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
std::cout << "pop" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
std::cout << "\n --> Number of Evaluations = " << eval.getValue() << std::endl;
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,108 @@
//-----------------------------------------------------------------------------
// t-eoMGE.cpp
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef __GNUG__
// to avoid long name warnings
#pragma warning(disable:4786)
#endif // __GNUG__
#include <eo>
#include <ga/eoBitOp.h>
#include "RoyalRoad.h"
// Viri
#include "VirusOp.h"
#include "eoVirus.h"
#include "eoInitVirus.h"
//-----------------------------------------------------------------------------
typedef eoVirus<float> Chrom;
//-----------------------------------------------------------------------------
int main()
{
const unsigned POP_SIZE = 10, CHROM_SIZE = 12;
unsigned i;
eoBooleanGenerator gen;
// the populations:
eoPop<Chrom> pop;
// Evaluation
RoyalRoad<Chrom> rr( 8 );
eoEvalFuncCounter<Chrom> eval( rr );
eoInitVirus<float> random(CHROM_SIZE, gen);
for (i = 0; i < POP_SIZE; ++i) {
Chrom chrom;
random(chrom);
eval(chrom);
pop.push_back(chrom);
}
std::cout << "population:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
// selection
eoStochTournamentSelect<Chrom> lottery(0.9 );
// breeder
VirusMutation<float> vm;
VirusTransmission<float> vt;
VirusBitFlip<float> vf;
eoUBitXover<Chrom> xover;
eoProportionalOp<Chrom> propSel;
eoGeneralBreeder<Chrom> breeder( lottery, propSel );
propSel.add(vm, 0.1);
propSel.add(vf, 0.05);
propSel.add(vt, 0.05);
propSel.add(xover, 0.8);
// Replace a single one
eoCommaReplacement<Chrom> replace;
// Terminators
eoGenContinue<Chrom> continuator1(10);
eoFitContinue<Chrom> continuator2(CHROM_SIZE);
eoCombinedContinue<Chrom> continuator(continuator1, continuator2);
eoCheckPoint<Chrom> checkpoint(continuator);
eoStdoutMonitor monitor;
checkpoint.add(monitor);
eoSecondMomentStats<Chrom> stats;
eoPopStat<Chrom> dumper( 10 );
monitor.add(stats);
checkpoint.add(dumper);
checkpoint.add(stats);
// GA generation
eoEasyEA<Chrom> ea(checkpoint, eval, breeder, replace );
// evolution
try
{
ea(pop);
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
std::cout << "pop" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
std::cout << "\n --> Number of Evaluations = " << eval.getValue() << std::endl;
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,111 @@
//-----------------------------------------------------------------------------
// t-eoMGE.cpp
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef __GNUG__
// to avoid long name warnings
#pragma warning(disable:4786)
#endif // __GNUG__
#include "eo"
#include "ga/eoBitOp.h"
#include "RoyalRoad.h"
// Viri
#include "VirusOp.h"
#include "eoVirus.h"
#include "eoInitVirus.h"
//-----------------------------------------------------------------------------
typedef eoVirus<double> Chrom;
//-----------------------------------------------------------------------------
int main()
{
const unsigned POP_SIZE = 10, CHROM_SIZE = 12;
unsigned i;
eoBooleanGenerator gen;
// the populations:
eoPop<Chrom> pop;
// Evaluation
RoyalRoad<Chrom> rr( 8 );
eoEvalFuncCounter<Chrom> eval( rr );
eoInitVirus1bit<double> random(CHROM_SIZE, gen);
for (i = 0; i < POP_SIZE; ++i) {
Chrom chrom;
random(chrom);
eval(chrom);
pop.push_back(chrom);
}
std::cout << "population:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
// selection
eoStochTournamentSelect<Chrom> lottery(0.9 );
// breeder
VirusShiftMutation<double> vm;
VirusTransmission<double> vt;
VirusBitFlip<double> vf;
eoUBitXover<Chrom> xover;
eoProportionalOp<Chrom> propSel;
eoGeneralBreeder<Chrom> breeder( lottery, propSel );
propSel.add(vm, 0.8);
propSel.add(vf, 0.05);
propSel.add(vt, 0.05);
propSel.add(xover, 0.1);
// Replace a single one
eoCommaReplacement<Chrom> replace;
// Terminators
eoGenContinue<Chrom> continuator1(10);
eoFitContinue<Chrom> continuator2(CHROM_SIZE);
eoCombinedContinue<Chrom> continuator(continuator1, continuator2);
eoCheckPoint<Chrom> checkpoint(continuator);
eoStdoutMonitor monitor;
checkpoint.add(monitor);
eoSecondMomentStats<Chrom> stats;
eoPopStat<Chrom> dumper( 10 );
monitor.add(stats);
checkpoint.add(dumper);
checkpoint.add(stats);
// GA generation
eoEasyEA<Chrom> ea(checkpoint, eval, breeder, replace);
// evolution
try {
ea(pop);
} catch (std::exception& e) {
std::cerr << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
std::cout << "pop" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
std::cout << "\n --> Number of Evaluations = " << eval.getValue() << std::endl;
return EXIT_SUCCESS;
}
//-----------------------------------------------------------------------------
// Local Variables:
// mode: C++
// c-file-style: "Stroustrup"
// End:

View file

@ -0,0 +1,14 @@
#include <eo>
typedef EO<float> Chrom;
int main()
{
Chrom chrom1, chrom2;
// EO objects can be printed with stream operators
std::cout << "chrom1 = " << chrom1 << std::endl
<< "chrom2 = " << chrom2 << std::endl;
return 0;
}

View file

@ -0,0 +1,220 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
/*
-----------------------------------------------------------------------------
File............: t-eo2dVector.cc
Author..........: Geneura Team (this file: Victor Rivas, vrivas@ujaen.es)
Date............: 01-Oct-1999, at Fac. of Sciences, Univ. of Granada (Spain)
Description.....: Test for 2 dimensional eoVector.
================ Modif. 1 ================
Author........:
Date..........:
Description...:
-----------------------------------------------------------------------------
*/
#include <stdexcept>
#include <eo2dVector.h> // eo2dVector
#include <eoUniform.h> // Random generator
//-----------------------------------------------------------------------------
typedef unsigned T;
typedef double fitnessT;
typedef eo2dVector<T,fitnessT> C;
//-----------------------------------------------------------------------------
main()
{
{
C c1;
cout << "Default constructor: " << endl
<< c1 << endl;
}
{
C c1( 5,6,1 );
cout << "Default constructor with values: " << endl
<< c1 << endl;
}
{
eoUniform<T> aleat( 1,10 );
C c1( 5,6, aleat );
cout << "Random constructor: " << endl
<< c1 << endl;
}
{
C c1( 3,4,1 ), c2( c1 );
cout << "Copy constructor: " << endl
<< "Original chromosome: " << endl
<< c1 << endl
<< "Copy chromosome: " << endl
<< c2 << endl;
}
eoUniform<T> aleat( 1,10 );
C c1( 3,4,aleat );
cout << "-----------------------------------------------------" << endl
<< "Since now on all the operations are applied to " << endl
<< c1
<< "-----------------------------------------------------" << endl;
{
cout << "getGene(2,2): "
<< c1.getGene(2,2) << endl;
}
{
c1.setGene( 2,2,300 );
cout << "setGene(2,2,300): " << endl
<< c1 << endl;
}
{
unsigned u1=0, u3=333, u5=555;
vector<T> v1( 4,u1 ), v2( 4,u3 ), v3( 4,u5 );
c1.insertRow( 0,v1 );
c1.insertRow( 3,v2 );
c1.insertRow( 5,v3 );
cout << "Insert rows at positions 0, 3 and 5: " << endl
<< c1 << endl;
}
{
c1.deleteRow( 5 );
c1.deleteRow( 3 );
c1.deleteRow( 0 );
cout << "Delete rows at positions 5, 3 and 0: " << endl
<< c1 << endl;
}
{
unsigned u1=0, u3=333, u6=666;
vector<T> v1( 3,u1 ), v2( 3,u3 ), v3( 3,u6 );
c1.insertCol( 0,v1 );
c1.insertCol( 3,v2 );
c1.insertCol( 6,v3 );
cout << "Insert columns at positions 0, 3 and 6: " << endl
<< c1 << endl;
}
{
c1.deleteCol( 6 );
c1.deleteCol( 3 );
c1.deleteCol( 0 );
cout << "Delete columns at positions 6, 3 and 0: " << endl
<< c1 << endl;
}
{
cout << "Number of Rows: " << endl
<< c1.numOfRows() << endl;
}
{
cout << "Number of Columns: " << endl
<< c1.numOfCols() << endl;
}
{
cout << "Class Name: " << endl
<< c1.className() << endl;
}
cout << "-----------------------------------------------------" << endl
<< "Catching exceptions: " << endl
<< c1
<< "-----------------------------------------------------" << endl;
{
cout << "* Trying getGene(10,1): " << endl;
try {
c1.getGene( 10,1 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
cout << "* Trying getGene(1,10): " << endl;
try {
c1.getGene( 1,10) ;
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
cout << "* Trying setGene( 10,1,999 ): " << endl;
try {
c1.setGene( 10,1,999 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
cout << "* Trying setGene( 1,10,999 ): " << endl;
try {
c1.setGene( 1,10,999 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
unsigned u1=111;
vector<T> v1( 4, u1 );
cout << "* Trying insertRow( 10, v1 ): " << endl;
try {
c1.insertRow( 10,v1 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
unsigned u1=111;
vector<T> v1( 5, u1 );
cout << "* Trying insertRow( 1, v1 ) with v1.size()=5: " << endl;
try {
c1.insertRow( 1,v1 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
cout << "* Trying deleteRow( 10 ): " << endl;
try {
c1.deleteRow( 10 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
unsigned u1=111;
vector<T> v1( 3, u1 );
cout << "* Trying insertCol( 10,v1 ): " << endl;
try {
c1.insertCol( 10,v1 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
unsigned u1=111;
vector<T> v1( 5, u1 );
cout << "* Trying insertCol( 1,v1 ) with v1.size()=5: " << endl;
try {
c1.insertCol( 1,v1 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
{
cout << "* Trying deleteCol( 10 ): " << endl;
try {
c1.deleteCol( 10 );
} catch (exception& e ) {
cerr << e.what() << endl;
}
}
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,124 @@
#include <iostream>
#include <eoScalarFitness.h>
#include <eoVector.h>
#include <eoPop.h>
#include <utils/eoParser.h>
#include <utils/eoCheckPoint.h>
#include <eoEvalFuncPtr.h>
#include <eoGenContinue.h>
#include <eoFitContinue.h>
#include <utils/eoStdoutMonitor.h>
#include <utils/eoStat.h>
#include <utils/eoTimedMonitor.h>
#include <eoMergeReduce.h>
#include <eoEasyEA.h>
#include <es/CMAState.h>
#include <es/CMAParams.h>
#include <es/eoCMAInit.h>
#include <es/eoCMABreed.h>
using namespace eo;
using namespace std;
typedef eoMinimizingFitness FitT;
typedef eoVector<FitT, double> EoType;
double sqr(double x) { return x*x; }
eoValueParam<int> evals(0,"Function Evals","Number of Evaluations");
double f_sphere(const vector<double>& values) {
double sum = 0.0;
for (unsigned i = 0; i < values.size(); ++i) {
sum += values[i] * values[i];
}
++evals.value();
return sum;
}
double f_rosen(const vector<double>& x) {
double sum =0.0;
for (unsigned i = 0; i < x.size()-1; ++i) {
sum += 100 * sqr(sqr(x[i])-x[i+1]) + sqr(1.-x[i]);
}
++evals.value();
return sum;
}
int main(int argc, char* argv[]) {
// make sure we have a dimensionality parameter (for testing)
char** rargv = new char*[argc+1];
rargv[0] = argv[0];
rargv[1] = (char*)"-N10";
for (int i = 2; i < argc; ++i) {
rargv[i] = argv[i-1];
}
eoParser parser(argc+1, rargv);
CMAParams params(parser);
vector<double> initial_point(params.n, 0.0);
CMAState state(params, initial_point);
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
return 1;
}
eoCMAInit<FitT> init(state);
eoPop<EoType> pop(params.mu, init);
eoEvalFuncPtr<EoType, double, const vector<double>&> eval( f_rosen );
eoCMABreed<FitT> breed(state, params.lambda);
for (unsigned i = 0; i < pop.size(); ++i) {
eval(pop[i]);
}
eoCommaReplacement<EoType> comma;
eoGenContinue<EoType> gen(params.maxgen);
eoFitContinue<EoType> fit(1e-10);
eoCheckPoint<EoType> checkpoint(gen);
checkpoint.add(fit);
eoBestFitnessStat<EoType> stat;
eoStdoutMonitor mon;
mon.add(stat);
mon.add(evals);
eoTimedMonitor timed(1);// 1 seconds
timed.add(mon); // wrap it
checkpoint.add(timed);
checkpoint.add(stat);
eoEasyEA<EoType> algo(
checkpoint,
eval,
breed,
comma);
algo(pop);
pop.sort();
cout << pop[0] << endl;
cout << "Fitness achieved = " << pop[0].fitness() << endl;
cout << "Function evaluations = " << evals.value() << endl;
}

View file

@ -0,0 +1,173 @@
// to avoid long name warnings
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <stdexcept> // runtime_error
// general
#include <utils/eoRNG.h> // Random number generators
#include <ga.h>
#include <utils/eoParser.h>
#include <utils/eoState.h>
#include <eoGenContinue.h>
// include package checkpointing
#include <utils/checkpointing>
struct Dummy : public EO<double>
{
typedef double Type;
};
struct eoDummyPop : public eoPop<Dummy>
{
public :
eoDummyPop(int s = 2) { resize(s); }
};
int the_main(int argc, char **argv)
{ // ok, we have a command line parser and a state
typedef eoBit<float> Chrom;
eoParser parser(argc, argv);
// Define Parameters
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<uint32_t> seed(time(0), "seed", "Random number seed");
eoValueParam<std::string> load_name("", "Load","Load",'L');
eoValueParam<std::string> save_name("", "Save","Save",'S');
// Register them
parser.processParam(rate, "Genetic Operators");
parser.processParam(factor, "Genetic Operators");
parser.processParam(load_name, "Persistence");
parser.processParam(save_name, "Persistence");
parser.processParam(seed, "Rng seeding");
eoState state;
state.registerObject(parser);
if (load_name.value() != "")
{ // 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<EoType> genTerm(5); // run for 5 generations
eoCheckPoint<EoType> checkpoint(genTerm);
// The algorithm will now quit after five generations
// Create a counter parameter
eoValueParam<unsigned> generationCounter(0, "Generation");
// 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<unsigned> increment(generationCounter.value());
// Add it to the checkpoint, this will result in the counter being incremented every generation
checkpoint.add(increment);
// 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);
// the monitor can monitor parameters such as the generationCounter
monitor.add(generationCounter);
// Second moment stats: average and stdev
eoSecondMomentStats<EoType> stats;
// Add it to the checkpoint to get it called at the appropriate time
checkpoint.add(stats);
// Add it to the monitor to get it written to the file
monitor.add(stats);
// save state every third generation
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);
checkpoint.add(stateSaver2);
// Register the algorithm
state.registerObject(rng);
state.registerObject(pop);
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
return 0;
}
// Either load or initialize
if (load_name.value() != "")
{
state.load(load_name.value()); // load the rest
}
else
{
// else
// initialize rng and population
rng.reseed(seed.value());
pop.resize(2);
pop[0].fitness(1);
pop[1].fitness(2);
}
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
std::cout << "gen " << generationCounter.value() << std::endl;
}
// run the algorithm
// Save when needed
if (save_name.value() != "")
{
std::string file_name = save_name.value();
save_name.value() = ""; // so that it does not appear in the parser section of the state file
state.save(file_name);
}
return 1;
}
int main(int argc, char **argv)
{
try
{
the_main(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
}

View file

@ -0,0 +1,88 @@
#include <utility>
#include <eo>
#include <es.h>
#include <utils/eoStat.h>
typedef eoVector<eoDualFitness<double,eoMinimizingFitness>,double> DualVector;
template<class EOT>
class DualSphere : public eoEvalFunc<EOT>
{
public:
virtual void operator()( EOT & x )
{
if( x.invalid() ) { return; }
double sum = 0;
int sign = 1;
for( unsigned int i=0, s=x.size(); i<s; ++i ) {
sum += x[i] * x[i];
sign *= x[i]<0 ? -1 : 1;
}
x.fitness( std::make_pair( sum, sign>0 ? true : false ) );
}
};
double test( eoPop<DualVector>& pop, double target_value )
{
DualSphere<DualVector> eval;
eoPopLoopEval<DualVector> pop_eval(eval);
pop_eval(pop,pop);
eoInterquartileRangeStat<DualVector> iqr_stat( std::make_pair(0.0,false), "IQR" );
iqr_stat( pop );
std::cout << iqr_stat.longName() << "=" << iqr_stat.value() << " should be " << target_value << std::endl;
return iqr_stat.value().value();
}
int main()
{
eoPop<DualVector> pop;
// fixed test
DualVector sol1(2,-1);
DualVector sol2(2,-1);
DualVector sol3(2,1);
DualVector sol4(2,1);
pop.push_back( sol1 );
pop.push_back( sol2 );
pop.push_back( sol3 );
pop.push_back( sol4 );
// on the sphere function everyone has the same fitness of 1
if( test(pop, 0) != 0 ) {
exit(1);
}
pop.erase(pop.begin(),pop.end());
// fixed test
sol1 = DualVector(2,0);
sol2 = DualVector(2,0);
sol3 = DualVector(2,1);
sol4 = DualVector(2,1);
pop.push_back( sol1 );
pop.push_back( sol2 );
pop.push_back( sol3 );
pop.push_back( sol4 );
if( test(pop, 1) != 1 ) {
exit(1);
}
// test on a random normal distribution
eoNormalGenerator<double> normal(1,rng);
eoInitFixedLength<DualVector> init_N(2, normal);
pop = eoPop<DualVector>( 1000000, init_N );
double iqr = test(pop, 1.09);
if( iqr < 1.08 || iqr > 1.11 ) {
exit(1);
}
}

View file

@ -0,0 +1,150 @@
// Program to test several EO-ES features
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <algorithm>
#include <string>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <ctime>
#ifdef _MSC_VER
#include <crtdbg.h>
#endif
using namespace std;
#include <eo>
// representation specific
#include <es/make_es.h>
#include "real_value.h" // the sphere fitness
// Now the main
///////////////
typedef eoMinimizingFitness FitT;
template <class EOT>
void runAlgorithm(EOT, eoParser& _parser, eoState& _state);
int main_function(int argc, char *argv[])
{
// Create the command-line parser
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
eoValueParam<bool>& simpleParam = parser.getORcreateParam(true, "Isotropic",
"Isotropic self-adaptive mutation",
'i', "ES mutation");
eoValueParam<bool>& stdevsParam = parser.getORcreateParam(false, "Stdev",
"One self-adaptive stDev per variable",
's', "ES mutation");
eoValueParam<bool>& corrParam = parser.getORcreateParam(false, "Correl",
"Use correlated mutations",
'c', "ES mutation");
// Run the appropriate algorithm
if (simpleParam.value() == false)
{
std::cout << "Using eoReal" << std::endl;
runAlgorithm(eoReal<FitT>(), parser, state);
}
else if (stdevsParam.value() == false)
{
std::cout << "Using eoEsSimple" << std::endl;
runAlgorithm(eoEsSimple<FitT>(), parser, state);
}
else if (corrParam.value() == false)
{
std::cout << "Using eoEsStdev" << std::endl;
runAlgorithm(eoEsStdev<FitT>(), parser, state);
}
else
{
std::cout << "Using eoEsFull" << std::endl;
runAlgorithm(eoEsFull<FitT>(), parser, state);
}
return 0;
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
#ifdef _MSC_VER
// rng.reseed(42);
int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
flag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(flag);
// _CrtSetBreakAlloc(100);
#endif
try
{
main_function(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << '\n';
}
}
/** The templatized main (sort of)
quite similar to the main of other genotypes (e.g. t-eoReal and t-eoGA
in test dir)
*/
template <class EOT>
void runAlgorithm(EOT, eoParser& _parser, eoState& _state)
{
typedef typename EOT::Fitness FitT;
///// FIRST, problem or representation dependent stuff
//////////////////////////////////////////////////////
// The evaluation fn - encapsulated into an eval counter for output
eoEvalFuncPtr<EOT, double, const std::vector<double>&> mainEval( real_value );
eoEvalFuncCounter<EOT> eval(mainEval);
// the genotype - through a genotype initializer
eoRealInitBounded<EOT>& init = make_genotype(_parser, _state, EOT());
// Build the variation operator (any seq/prop construct)
eoGenOp<EOT>& op = make_op(_parser, _state, init);
//// Now the representation-independent things
//////////////////////////////////////////////
// initialize the population - and evaluate
// yes, this is representation indepedent once you have an eoInit
eoPop<EOT>& pop = make_pop(_parser, _state, init);
apply<EOT>(eval, pop);
// stopping criteria
eoContinue<EOT> & term = make_continue(_parser, _state, eval);
// output
eoCheckPoint<EOT> & checkpoint = make_checkpoint(_parser, _state, eval, term);
// algorithm (need the operator!)
eoAlgo<EOT>& ga = make_algo_scalar(_parser, _state, eval, checkpoint, op);
///// End of construction of the algorith
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(_parser);
//// GO
///////
std::cout << "Initial Population\n";
pop.sortedPrintOn(std::cout);
std::cout << std::endl;
run_ea(ga, pop); // run the ga
std::cout << "Final Population\n";
pop.sortedPrintOn(std::cout);
std::cout << std::endl;
}

View file

@ -0,0 +1,180 @@
// Program to test several EO-ES features
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <algorithm>
#include <string>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <time.h>
using namespace std;
#include <eo>
// representation specific
#include <es.h>
#include "real_value.h" // the sphere fitness
// Now the main
///////////////
typedef eoMinimizingFitness FitT;
template <class EOT>
void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam<string> _load_name);
int main_function(int argc, char *argv[])
{
// Create the command-line parser
eoParser parser( argc, argv, "Basic EA for vector<float> with adaptive mutations");
// Define Parameters and load them
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>& 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>& corr = parser.createParam(false, "Correl", "Use correlated mutations", 'c');
eoValueParam<unsigned>& chromSize = parser.createParam(unsigned(50), "ChromSize", "Number of chromosomes", 'n');
eoValueParam<double>& minimum = parser.createParam(-1.0, "Min", "Minimum for Objective Variables", 'l');
eoValueParam<double>& maximum = parser.createParam(1.0, "Max", "Maximum for Objective Variables", 'h');
eoState state;
state.registerObject(parser);
rng.reseed(seed.value());
if (!load_name.value().empty())
{ // 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!.
state.load(load_name.value()); // load the parser
}
state.registerObject(rng);
eoRealVectorBounds bounds(chromSize.value(), minimum.value(), maximum.value());
// Run the appropriate algorithm
if (stdevs.value() == false && corr.value() == false)
{
runAlgorithm(eoEsSimple<FitT>() ,parser, state, bounds, load_name);
}
else if (corr.value() == true)
{
runAlgorithm(eoEsFull<FitT>(),parser, state, bounds, load_name);
}
else
{
runAlgorithm(eoEsStdev<FitT>(), parser, state, bounds, load_name);
}
// and save
if (!save_name.value().empty())
{
string file_name = save_name.value();
save_name.value() = ""; // so that it does not appear in the parser section of the state file
state.save(file_name);
}
return 0;
}
// A main that catches the exceptions
int main(int argc, char **argv)
{
#ifdef _MSC_VER
// rng.reseed(42);
int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
flag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(flag);
// _CrtSetBreakAlloc(100);
#endif
try
{
main_function(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << '\n';
}
return 1;
}
template <class EOT>
void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam<string> _load_name)
{
// evaluation
eoEvalFuncPtr<EOT, double, const vector<double>&> eval( real_value );
// population parameters, unfortunately these can not be altered in the state file
eoValueParam<unsigned> mu = _parser.createParam(unsigned(7), "mu","Size of the population");
eoValueParam<double>lambda_rate = _parser.createParam(double(7.0), "lambda_rate", "Factor of children to produce");
if (lambda_rate.value() < 1.0f)
{
throw logic_error("lambda_rate must be larger than 1 in a comma strategy");
}
// Initialization
eoEsChromInit<EOT> init(_bounds);
// State takes ownership of pop because it needs to save it in caller
eoPop<EOT>& pop = _state.takeOwnership(eoPop<EOT>(mu.value(), init));
_state.registerObject(pop);
if (!_load_name.value().empty())
{ // The real loading happens here when all objects are registered
_state.load(_load_name.value()); // load all and everything
}
else
{
// evaluate initial population
apply<EOT>(eval, pop);
}
// Ok, time to set up the algorithm
// Proxy for the mutation parameters
eoEsMutationInit mutateInit(_parser);
eoEsMutate<EOT> mutate(mutateInit, _bounds);
// monitoring, statistics etc.
eoAverageStat<EOT> average;
eoStdoutMonitor monitor;
monitor.add(average);
eoGenContinue<EOT> cnt(100);
eoCheckPoint<EOT> checkpoint(cnt);
checkpoint.add(monitor);
checkpoint.add(average);
// only mutation (== with rate 1.0)
eoMonGenOp<EOT> op(mutate);
// the selection: sequential selection
eoSequentialSelect<EOT> select;
// the general breeder (lambda is a rate -> true)
eoGeneralBreeder<EOT> breed(select, op, lambda_rate.value(), true);
// the replacement - hard-coded Comma replacement
eoCommaReplacement<EOT> replace;
// now the eoEasyEA
eoEasyEA<EOT> es(checkpoint, eval, breed, replace);
es(pop);
pop.sort();
std::cout << "Final population\n" << pop << std::endl;
}

View file

@ -0,0 +1,74 @@
#ifndef __GNUG__
// to avoid long name warnings
#pragma warning(disable:4786)
#endif // __GNUG__
#include <eo>
#include "binary_value.h"
typedef eoBin<float> Chrom;
main()
{
const unsigned POP_SIZE = 8, CHROM_SIZE = 16;
unsigned i;
// a chromosome randomizer
eoBinRandom<Chrom> random;
// the populations:
eoPop<Chrom> pop;
// Evaluation
eoEvalFuncPtr<Chrom> eval( binary_value );
for (i = 0; i < POP_SIZE; ++i)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
eval(chrom);
pop.push_back(chrom);
}
std::cout << "population:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
// selection
eoLottery<Chrom> lottery;
// breeder
eoBinBitFlip<Chrom> bitflip;
eoBinCrossover<Chrom> xover;
eoProportionalOpSel<Chrom> propSel;
eoBreeder<Chrom> breeder( propSel );
propSel.addOp(bitflip, 0.25);
propSel.addOp(xover, 0.75);
// replacement
eoInclusion<Chrom> inclusion;
// Terminators
eoFitTerm<Chrom> term( pow(2.0, CHROM_SIZE), 1 );
// GA generation
eoEasyEA<Chrom> ea(lottery, breeder, inclusion, eval, term);
// evolution
try
{
ea(pop);
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
std::cout << "pop" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
return 0;
}

View file

@ -0,0 +1,102 @@
//-----------------------------------------------------------------------------
// t-eoEasyPSO.cpp
//-----------------------------------------------------------------------------
#ifndef __GNUG__
// to avoid long name warnings
#pragma warning(disable:4786)
#endif // __GNUG__
#include <eo>
//-----------------------------------------------------------------------------
typedef eoMinimizingFitness FitT;
typedef eoRealParticle < FitT > Particle;
//-----------------------------------------------------------------------------
// the objective function
double real_value (const Particle & _particle)
{
double sum = 0;
for (unsigned i = 0; i < _particle.size ()-1; i++)
sum += pow(_particle[i],2);
return (sum);
}
int main()
{
const unsigned int VEC_SIZE = 2;
const unsigned int POP_SIZE = 20;
const unsigned int NEIGHBORHOOD_SIZE= 5;
unsigned i;
// the population:
eoPop<Particle> pop;
// Evaluation
eoEvalFuncPtr<Particle, double, const Particle& > eval( real_value );
// position init
eoUniformGenerator < double >uGen (-3, 3);
eoInitFixedLength < Particle > random (VEC_SIZE, uGen);
// velocity init
eoUniformGenerator < double >sGen (-2, 2);
eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen);
// local best init
eoFirstIsBestInit < Particle > localInit;
// perform position initialization
pop.append (POP_SIZE, random);
// topology
eoLinearTopology<Particle> topology(NEIGHBORHOOD_SIZE);
// the full initializer
eoInitializer <Particle> init(eval,veloRandom,localInit,topology,pop);
init();
// bounds
eoRealVectorBounds bnds(VEC_SIZE,-1.5,1.5);
// velocity
eoStandardVelocity <Particle> velocity (topology,1,1.6,2,bnds);
// flight
eoStandardFlight <Particle> flight;
// Terminators
eoGenContinue <Particle> genCont1 (50);
eoGenContinue <Particle> genCont2 (50);
// PS flight
eoEasyPSO<Particle> pso1(genCont1, eval, velocity, flight);
eoEasyPSO<Particle> pso2(init,genCont2, eval, velocity, flight);
// flight
try
{
pso1(pop);
std::cout << "FINAL POPULATION AFTER PSO n°1:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
pso2(pop);
std::cout << "FINAL POPULATION AFTER PSO n°2:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
return 0;
}

View file

@ -0,0 +1,76 @@
//-----------------------------------------------------------------------------
// t-eoExtendedVelocity.cpp
//-----------------------------------------------------------------------------
#include <eo>
typedef eoRealParticle < double > Particle;
//Evaluation function
double f (const Particle & _particle)
{
double sum = 0;
for (unsigned i = 0; i < _particle.size (); i++)
sum += pow(_particle[i],2);
return (-sum);
}
int main_function(int argc, char **argv)
{
const unsigned POP_SIZE = 6, VEC_SIZE = 2, NEIGHBORHOOD_SIZE=2;
// the population:
eoPop<Particle> pop;
// Evaluation
eoEvalFuncPtr<Particle, double, const Particle& > eval( f );
// position + velocity + best init
eoUniformGenerator < double >uGen (-3, 3);
eoInitFixedLength < Particle > random (VEC_SIZE, uGen);
eoUniformGenerator < double >sGen (-2, 2);
eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen);
eoFirstIsBestInit < Particle > localInit;
pop.append (POP_SIZE, random);
// topology
eoLinearTopology<Particle> topology(NEIGHBORHOOD_SIZE);
eoInitializer <Particle> init(eval,veloRandom,localInit,topology,pop);
init();
// velocity
eoExtendedVelocity <Particle> velocity (topology,1,1,1,1);
// the test itself
for (unsigned int i = 0; i < POP_SIZE; i++)
{
std::cout << " Initial particle n°" << i << " velocity: " << std::endl;
for (unsigned int j = 0; j < VEC_SIZE; j++)
std::cout << " v" << j << "=" << pop[i].velocities[j] << std::endl;
}
for (unsigned int i = 0; i < POP_SIZE; i++)
velocity (pop[i],i);
for (unsigned int i = 0; i < POP_SIZE; i++)
{
std::cout << " Final particle n°" << i << " velocity: " << std::endl;
for (unsigned int j = 0; j < VEC_SIZE; j++)
std::cout << " v" << j << "=" << pop[i].velocities[j] << std::endl;
}
return EXIT_SUCCESS;
}
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << " in t-eoExtendedVelocity" << std::endl;
}
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,132 @@
// to avoid long name warnings
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <iostream>
#include <stdexcept> // runtime_error
#include <eoEvalFuncPtr.h>
#include <other/external_eo>
#include <utils/eoRNG.h>
using namespace std;
struct UserDefStruct
{
int a;
float b;
double c;
enum Enum { just, another, test } d;
};
std::ostream& operator<<(std::ostream& os, const UserDefStruct& str)
{
return os << str.a << ' ' << str.b << ' ' << str.c << ' ' << static_cast<int>(str.d) << ' ';
}
istream& operator>>(istream& is, UserDefStruct& str)
{
is >> str.a;
is >> str.b;
is >> str.c;
int i;
is >> i;
str.d = static_cast<UserDefStruct::Enum>(i);
return is;
}
UserDefStruct RandomStruct()
{
std::cout << "RandomStruct\n";
UserDefStruct result;
result.a = rng.random(5);
result.b = rng.uniform();
result.c = rng.uniform();
result.d = UserDefStruct::another;
return result;
}
// reading and writing
bool UserDefMutate(UserDefStruct& a)
{
std::cout << "UserDefMutate\n";
a = RandomStruct(); // just for testing
if (rng.flip(0.1f))
a.d = UserDefStruct::test;
else
a.d = UserDefStruct::another;
return true;
}
bool UserDefBinCrossover(UserDefStruct& a, const UserDefStruct& b)
{
std::cout << "UserDefBinCrossover\n";
if (rng.flip(0.5))
a.a = b.a;
if (rng.flip(0.5))
a.b = b.b;
if (rng.flip(0.5))
a.c = b.c;
if (rng.flip(0.5))
a.d = b.d;
return true;
}
bool UserDefQuadCrossover(UserDefStruct& a, UserDefStruct& b)
{
std::cout << "UserDefQuadCrossover\n";
if (rng.flip(0.5))
swap(a.a, b.a);
if (rng.flip(0.5))
swap(a.b, b.b);
if (rng.flip(0.5))
swap(a.c, b.c);
if (rng.flip(0.5))
swap(a.d, b.d);
return true;
}
float UserDefEvalFunc(const UserDefStruct& a)
{
std::cout << "UserDefEvalFunc\n";
return a.b;
}
int main()
{
typedef UserDefStruct External;
typedef float FitnessType;
typedef eoExternalEO<float, External> EoType;
eoExternalInit<FitnessType, External> init(RandomStruct);
eoExternalMonOp<FitnessType, External> mutate(UserDefMutate);
eoExternalBinOp<FitnessType, External> cross1(UserDefBinCrossover);
eoExternalQuadOp<FitnessType, External> cross2(UserDefQuadCrossover);
// eoExternalEvalFunc<FitnessType, External> eval(UserDefEvalFunc);
EoType eo1;
init(eo1);
EoType eo2;
init(eo2);
std::cout << "before mutation " << eo1 << '\n';
mutate(eo1);
std::cout << "after mutation " << eo1 << '\n';
cross1(eo1, eo2);
std::cout << "after crossover " << eo1 << '\n';
cross2(eo1,eo2);
}

View file

@ -0,0 +1,104 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// t-eoFitnessAssembled.cpp
// Marc Wintermantel & Oliver Koenig
// IMES-ST@ETHZ.CH
// March 2003
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@inria.fr
mak@dhi.dk
*/
//-----------------------------------------------------------------------------
#include <iostream>
#include <stdexcept>
#include "eoScalarFitnessAssembled.h"
void test_eoScalarFitnessAssembledClass(){
// Create instances
eoAssembledMinimizingFitness A,B,C(5, 1.3, "C value");
// Add some values to them
A.push_back( 5.6, "first value" );
A.push_back( 3.2, "second value" );
A.push_back( 2.6, "third value" );
B.push_back( 1.2 );
B.push_back( 3.2 );
B.push_back( 5.2 );
B.setDescription( 1, "B descr" );
std::cout << "Created instances A,B and C, added some vals; testing << operator " << std::endl;
std::cout << "A= " << A << std::endl;
std::cout << "B= " << B << std::endl;
std::cout << "C= " << C << std::endl;
std::cout << "Printing values and descriptions: " << std::endl;
std::cout << "A: "; A.printAll( std::cout ); std::cout << std::endl;
std::cout << "B: "; B.printAll( std::cout ); std::cout << std::endl;
std::cout << "C: "; C.printAll( std::cout ); std::cout << std::endl;
A.resize(8, 100.3, "A resized");
std::cout << "Resized A: "; A.printAll( std::cout ); std::cout << std::endl;
std::cout << "Access fitness values of A and B: " << "f(A)= " << (double) A << " f(B)= " << (double) B << std::endl;
// Testing constructors and assignments
eoAssembledMinimizingFitness D(A) ,E(3.2);
std::cout << "D(A) = " << D << "\t" << "E(3.2)= " << E << std::endl;
eoAssembledMinimizingFitness F,G;
F=A;
G= 7.5;
std::cout << "F = A : " << F << "\t G = 7.5 : " << G << std::endl;
// Comparing...
std::cout << "A<B: " << (A<B) << std::endl;
std::cout << "A>B: " << (A>B) << std::endl;
std::cout << "A<=B: " << (A<=B) << std::endl;
std::cout << "A>=B: " << (A>=B) << std::endl;
}
int main(){
std::cout << "-----------------------------------" << std::endl;
std::cout << "START t-eoFitnessAssembled" << std::endl;
try{
// Test the fitness class itself
test_eoScalarFitnessAssembledClass();
}
catch(std::exception& e){
std::cout << e.what() << std::endl;
return 1;
}
std::cout << "END t-eoFitnessAssembled" << std::endl;
std::cout << "----------------------------------" << std::endl;
return 0;
}

View file

@ -0,0 +1,174 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// t-eoFitnessAssembledEA.cpp
// Marc Wintermantel & Oliver Koenig
// IMES-ST@ETHZ.CH
// March 2003
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@inria.fr
mak@dhi.dk
*/
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <cmath>
// General eo includes
#include <eo>
#include <utils/eoRealVectorBounds.h> // The real bounds (not yet in general eo include)
// Representation dependent includes and typedefs
#include <es/eoReal.h> // Definition of representation
#include <es/eoRealInitBounded.h> // Uniformly initializes real vector in bounds
#include <es/make_genotype_real.h> // Initialization of a genotype
#include <eoEvalFunc.h> // Base class for fitness evaluation
#include <es/make_op_real.h> // Variation operators using standard Real operators
#include <eoScalarFitnessAssembled.h> // The fitness class
typedef eoReal<eoAssembledMinimizingFitness> Indi;
// Representation independent modules
#include <do/make_pop.h> // Initialization of population
#include <do/make_continue.h> // The stopping criterion
#include <do/make_checkpoint_assembled.h> // Outputs (stats, population dumps, ...)
#include <do/make_algo_scalar.h> // Evolution engine (selection and replacement)
#include <do/make_run.h> // simple call to the algo.stays there for consistency reasons
// Define a fitness class
template <class EOT>
class eoAssembledEvalFunc : public eoEvalFunc<EOT>{
public:
// Constructor defining number and descriptions of fitness terms
eoAssembledEvalFunc() {
// Define a temporary fitness object to have access to its static traits
typename EOT::Fitness tmpfit(3, 0.0);
tmpfit.setDescription(0,"Fitness");
tmpfit.setDescription(1,"Some Value");
tmpfit.setDescription(2,"Other Value");
}
void operator()(EOT& _eo){
// Define temporary fitness object
// (automatically gets initialized with size given in constructor)
typename EOT::Fitness tmpfit;
// Eval some dummy fitness
double sum1=0.0, sum2=0.0;
for (unsigned i=0; i < _eo.size(); ++i){
sum1 += _eo[i]*_eo[i];
sum2 += fabs(_eo[i]) + fabs(_eo[i]);
}
// Store some fitness terms
tmpfit[1]= sum1;
tmpfit[2]= sum2;
// Store the fitness
tmpfit = (sum1 + sum2)/_eo.size();
// Pass it
_eo.fitness( tmpfit );
}
};
// checks for help demand, and writes the status file and make_help; in libutils
void make_help(eoParser & _parser);
// now use all of the above, + representation dependent things
int main(int argc, char* argv[]){
std::cout << "-----------------------------------" << std::endl;
std::cout << "START t-eoFitnessAssembledEA" << std::endl;
try{
// Parser & State
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
////
// A) Representation dependent stuff
////
// The fitness
eoAssembledEvalFunc<Indi> plainEval;
// turn that object into an evaluation counter
eoEvalFuncCounter<Indi> eval(plainEval);
// The genotype
eoRealInitBounded<Indi>& init = do_make_genotype(parser, state, Indi() );
// The variation operators
eoGenOp<Indi>& op = do_make_op(parser, state, init);
////
// B) Create representation independent stuff
////
// initialize the population
// yes, this is representation indepedent once you have an eoInit
eoPop<Indi>& pop = do_make_pop(parser, state, init);
// stopping criteria
eoContinue<Indi> & term = do_make_continue(parser, state, eval);
// output
eoCheckPoint<Indi> & checkpoint = do_make_checkpoint_assembled(parser, state, eval, term);
// algorithm (need the operator!)
eoAlgo<Indi>& ga = do_make_algo_scalar(parser, state, eval, checkpoint, op);
make_help(parser); // To be called after all parameters have been read !
////
// C) Run the algorithm
////
// evaluate intial population AFTER help and status in case it takes time
apply<Indi>(eval, pop);
// if you want to print it out
std::cout << "Initial Population\n";
pop.sortedPrintOn(std::cout);
std::cout << std::endl;
do_run(ga, pop); // run the ga
std::cout << "Final Population\n";
pop.sortedPrintOn(std::cout);
std::cout << std::endl;
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
return 1;
}
std::cout << "-----------------------------------" << std::endl;
std::cout << "END t-eoFitnessAssembledEA" << std::endl;
return 0;
}

View file

@ -0,0 +1,48 @@
#include <eoInit.h>
#include <eoCounter.h>
void f(eoInit<int>& func)
{
int i;
func(i);
}
class Tester : public eoInit<int>
{
public :
void operator()(int& i)
{
i=1;
}
};
#include <iostream>
#include <eoFixedLength.h>
#include <eoVariableLength.h>
using namespace std;
int main(void)
{
Tester test;
eoFunctorStore store;
/// make a counter and store it in 'store'
eoInit<int>& cntr = make_counter(functor_category(test), test, store);
eoUnaryFunctorCounter<eoInit<int> > cntr2(test);
f(cntr);
f(cntr2);
f(cntr2);
f(test);
typedef eoVariableLength<double, int> EoType;
EoType eo;
eo.push_back(1);
eo.push_back(2);
return 1;
}

View file

@ -0,0 +1,72 @@
#include <iostream>
#include <ga/make_ga.h>
#include <eoEvalFuncPtr.h>
#include "binary_value.h"
#include <apply.h>
using namespace std;
int main(int argc, char* argv[])
{
try
{
typedef eoBit<double> EOT;
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
///// FIRST, problem or representation dependent stuff
//////////////////////////////////////////////////////
// The evaluation fn - encapsulated into an eval counter for output
eoEvalFuncPtr<EOT, double> mainEval( binary_value<EOT> );
eoEvalFuncCounter<EOT> eval(mainEval);
// the genotype - through a genotype initializer
eoInit<EOT>& init = make_genotype(parser, state, EOT());
// Build the variation operator (any seq/prop construct)
eoGenOp<EOT>& op = make_op(parser, state, init);
//// Now the representation-independent things
//////////////////////////////////////////////
// initialize the population - and evaluate
// yes, this is representation indepedent once you have an eoInit
eoPop<EOT>& pop = make_pop(parser, state, init);
// stopping criteria
eoContinue<EOT> & term = make_continue(parser, state, eval);
// output
eoCheckPoint<EOT> & checkpoint = make_checkpoint(parser, state, eval, term);
// algorithm (need the operator!)
eoAlgo<EOT>& ga = make_algo_scalar(parser, state, eval, checkpoint, op);
///// End of construction of the algorith
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(parser);
//// GO
///////
// evaluate intial population AFTER help and status in case it takes time
apply<EOT>(eval, pop);
// print it out
std::cout << "Initial Population\n";
pop.sortedPrintOn(std::cout);
std::cout << std::endl;
run_ea(ga, pop); // run the ga
std::cout << "Final Population\n";
pop.sortedPrintOn(std::cout);
std::cout << std::endl;
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}

View file

@ -0,0 +1,427 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// 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
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: mkeijzer@dhi.dk
Marc.Schoenauer@polytechnique.fr
*/
//-----------------------------------------------------------------------------
/** test program for the general operator - millenium version!
* uses dummy individuals
*/
#include <sstream>
#include <eo>
#include <eoPopulator.h>
#include <eoOpContainer.h>
struct Dummy : public EO<double>
{
Dummy(std::string _s="") : s(_s) {}
void printOn(std::ostream & _os) const
{
EO<double>::printOn(_os);
_os << " - " << s ;
}
std::string s;
};
typedef Dummy EOT;
unsigned int pSize; // global to be used as marker in the fitness
// DEFINITIONS of the eoOps
class monop : public eoMonOp<EOT>
{
public :
monop(char * _sig){sig=_sig;}
bool operator()(EOT& _eo)
{
_eo.s = sig + "(" + _eo.s + ")";
_eo.fitness(_eo.fitness()+pSize);
return false;
}
std::string className() const {return sig;}
private:
std::string sig;
};
class binop: public eoBinOp<EOT>
{
public :
bool operator()(EOT& _eo1, const EOT& _eo2)
{
_eo1.s = "bin(" + _eo1.s + "," + _eo2.s + ")";
double f= (_eo1.fitness()+_eo2.fitness()) * pSize;
_eo1.fitness(_eo1.fitness()+f);
return false;
}
std::string className() const {return "binop";}
};
class quadop: public eoQuadOp<EOT>
{
public :
std::string className() const {return "quadop";}
bool operator()(EOT& a, EOT& b)
{
EOT oi = a;
EOT oj = b;
a.s = "quad1(" + oi.s + "," + oj.s + ")";
b.s = "quad2(" + oj.s + "," + oi.s + ")";
double f= (a.fitness()+b.fitness()+2*pSize) * pSize;
a.fitness(a.fitness()+f);
b.fitness(b.fitness()+f);
return false;
}
};
// an eoQuadOp that does nothing
class quadClone: public eoQuadOp<EOT>
{
public :
std::string className() const {return "quadclone";}
bool operator()(EOT& , EOT& ) {return false;}
};
// User defined General Operator... adapted from Marc's example
class one2threeOp : public eoGenOp<EOT> // :-)
{
public:
unsigned max_production(void) { return 3; }
void apply(eoPopulator<EOT>& _plop)
{
EOT& eo = *_plop; // select the guy
++_plop; // advance
_plop.insert("v(" + eo.s + ", 1)");
++_plop;
_plop.insert("v(" + eo.s + ", 2)");
eo.s = "v(" + eo.s + ", 0)"; // only now change the thing
// oh right, and invalidate fitnesses
}
virtual std::string className() const {return "one2threeOp";}
};
class two2oneOp : public eoGenOp<EOT> // :-)
{
public:
unsigned max_production(void) { return 1; }
void apply(eoPopulator<EOT>& _plop)
{
EOT& eo = *_plop; // select the guy
const EOT& eo2 = _plop.select();
eo.s = "221(" + eo.s + ", " + eo2.s + ")";
// oh right, and invalidate fitnesses
}
virtual std::string className() const {return "two2oneOp";}
};
class three2threeOp : public eoGenOp<EOT> // :-)
{
public:
unsigned max_production(void) { return 3; }
void apply(eoPopulator<EOT>& _plop)
{
EOT& eo1 = *_plop; // select 1st guy
EOT& eo2 = *++_plop; // select 2nd guy
EOT& eo3 = *++_plop; // select 3rd guy
EOT a = eo1;
EOT b = eo2;
EOT c = eo3;
std::cout << "les selectionnes: a=" << a << " et b=" << b << " et c=" << c << std::endl;
eo1.s = "323-1(" + a.s + ", " + b.s + ", " + c.s + ")";
eo2.s = "323-2(" + a.s + ", " + b.s + ", " + c.s + ")";
eo3.s = "323-3(" + a.s + ", " + b.s + ", " + c.s + ")";
// oh right, and invalidate fitnesses
std::cout << "les enfants: a=" << eo1 << " et b=" << eo2 << " et c=" << eo3 << std::endl;
}
virtual std::string className() const {return "three2threeOp";}
};
// dummy intialization. Re-init if no pSize, resize first if pSize
void init(eoPop<Dummy> & _pop, unsigned _pSize)
{
if (_pSize)
{
_pop.resize(_pSize);
}
else
{
throw std::runtime_error("init pop with 0 size");
}
for (unsigned i=0; i<_pSize; i++)
{
std::ostringstream os;
os << i;
_pop[i] = Dummy(os.str());
_pop[i].fitness(i);
}
}
// ok, now for the real work
int the_main(int argc, char **argv)
{
eoParser parser(argc, argv);
eoValueParam<unsigned int> parentSizeParam(
parser.createParam(unsigned(10), "parentSize", "Parent size",'P'));
pSize = parentSizeParam.value(); // global variable
eoValueParam<uint32_t> seedParam(time(0), "seed", "Random number seed", 'S');
parser.processParam( seedParam );
eo::rng.reseed(seedParam.value());
// do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED
// i.e. in case you need parameters somewhere else, postpone these
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(1);
}
////////////////////////////////// define operators
monop mon((char*)"mon1");
monop clone((char*)"clone");
binop bin;
quadop quad;
quadClone quadclone;
// our own operator
one2threeOp o2t;
two2oneOp t2o;
three2threeOp t2t;
// a selector
eoDetTournamentSelect<EOT> select;
// and a recognizable selector for testing the inbedded selector mechanism
eoBestSelect<EOT> selectBest;
// proportional selection between quad and bin
// so we either do a quad or a bin
eoProportionalOp<EOT> pOp;
pOp.add(quad, 0.1);
pOp.add(bin, 0.1);
// sequential selection between pOp and mon
eoSequentialOp<EOT> sOp;
sOp.add(pOp, 0.9);
sOp.add(mon, 0.1);
// with one2three op
eoSequentialOp<EOT> sOp2;
sOp2.add(o2t, 1);
// sOp2.add(quad, 1);
// with three2three op
eoSequentialOp<EOT> sOp3;
sOp3.add(t2t, 1);
// eoSequentialOp<EOT> sOp3;
// sOp3.add(t2o, 1);
// sOp3.add(bin, 1);
// sOp3.add(quad, 1);
// try adding quads and bins to see what results you'll get
// now a sequential selection that is a simple "addition"
eoSequentialOp<EOT> sOpQuadPlusMon;
sOpQuadPlusMon.add(quad, 1);
sOpQuadPlusMon.add(mon, 1);
// this corresponds
eoProportionalOp<EOT> pOpSAGLike;
pOpSAGLike.add(sOpQuadPlusMon, 0.24);
pOpSAGLike.add(quad, 0.56);
pOpSAGLike.add(mon, 0.06);
pOpSAGLike.add(clone, 0.14);
// init
eoPop<EOT> pop;
eoPop<EOT> offspring;
init(pop, pSize);
// sort pop so seqPopulator is identical to SelectPopulator(SequentialSelect)
pop.sort();
std::cout << "Population initiale" << std::endl << pop << std::endl;
// To simulate SGA: first a prop between quadOp and quadClone
eoProportionalOp<EOT> pSGAOp;
pSGAOp.add(quad, 0.8);
pSGAOp.add(quadclone, 0.2);
// sequential selection between pSGAOp and mon
eoSequentialOp<EOT> virtualSGA;
virtualSGA.add(pSGAOp, 1.0);
virtualSGA.add(mon, 0.3);
eoSeqPopulator<EOT> popit(pop, offspring); // no selection, a copy of pop
// until we filled a new population
try
{
while (offspring.size() < pop.size())
{
virtualSGA(popit);
std::cout << "SeqPopulator boucle et incremente\n";
++popit;
}
}
catch(eoPopulator<EOT>::OutOfIndividuals&)
{
std::cout << "Warning: not enough individuals to handle\n";
}
std::swap(pop, offspring);
offspring.clear();
// ok, now print
std::cout << "Apres virtualSGA \n" << pop << std::endl;
init(pop, pSize);
std::cout << "=========================================================\n";
std::cout << "Now the eoSelectPopulator version !" << std::endl;
eoSequentialSelect<EOT> seqSelect;
// select.init(); should be sorted out: is it the setup method???
eoSelectivePopulator<EOT> it_step3(pop, offspring, seqSelect);
while (offspring.size() < 2*pop.size())
{
virtualSGA(it_step3);
std::cout << "SelectPopulator boucle et incremente\n";
++it_step3;
}
std::swap(pop, offspring);
offspring.clear();
// ok, now print
std::cout << "Apres SGA-like eoSelectivePopulator\n" << pop << std::endl;
std::cout << "=========================================================\n";
std::cout << "Now the pure addition !" << std::endl;
init(pop, pSize);
eoSelectivePopulator<EOT> it_step4(pop, offspring, seqSelect);
while (offspring.size() < 2*pop.size())
{
sOpQuadPlusMon(it_step4);
++it_step4;
}
std::swap(pop, offspring);
offspring.clear();
// ok, now print
std::cout << "Apres Quad+Mon ds un eoSelectivePopulator\n" << pop << std::endl;
// On teste 1->3
init(pop, pSize);
eoSelectivePopulator<EOT> it_step5(pop, offspring, seqSelect);
while (offspring.size() < 2*pop.size())
{
sOp2(it_step5);
++it_step5;
}
std::swap(pop, offspring);
offspring.clear();
// ok, now print
std::cout << "Apres 1->3 seul ds un eoSelectivePopulator\n" << pop << std::endl;
// On teste 3->3
init(pop, pSize);
eoSelectivePopulator<EOT> it_step6(pop, offspring, seqSelect);
while (offspring.size() < 2*pop.size())
{
sOp3(it_step6);
++it_step6;
}
std::swap(pop, offspring);
offspring.clear();
// ok, now print
std::cout << "Apres 3->3 seul ds un eoSelectivePopulator\n" << pop << std::endl;
return 1;
}
int main(int argc, char **argv)
{
try
{
the_main(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
}
/*
If you want to build an SGA, you will need a copying quad op:
class quadclone : ...
{
operator(EOT& a, EOT& b)
{
// do nothing
}
}
Then the SGA operator will look like:
quadop quad;
guadclone clone;
ProportionalGenOp pOp;
pOp.add(quad, 0.8);
pOp.add(clone, 0.2); // so 80% xover rate
SequentialGenOp sOp;
sOp.add(pOp, 1,0); // always try a xover (clone 20%)
sOp.add(mut, 0.1); // low mutation rate
will result in an algorithm with:
p_xover = 0.8
p_mut = 0.1;
p_reproduction = 0.2 * 0.9 = 0.18
this does not add up to 1 because xover and mutation can be applied to a single indi
So what do you think?
*/

View file

@ -0,0 +1,67 @@
#include <eo>
#include <es.h>
#include <utils/eoStat.h>
#include "real_value.h"
typedef eoReal<eoMinimizingFitness> realVec;
double test( eoPop<realVec>& pop, double target_value )
{
eoEvalFuncPtr<realVec, double, const std::vector<double>&> eval( real_value );
eoPopLoopEval<realVec> pop_eval(eval);
pop_eval(pop,pop);
eoInterquartileRangeStat<realVec> iqr_stat(0.0, "IQR");
iqr_stat( pop );
std::cout << iqr_stat.longName() << "=" << iqr_stat.value() << " should be " << target_value << std::endl;
return iqr_stat.value();
}
int main()
{
eoPop<realVec> pop;
// fixed test
realVec sol1(2,-1);
realVec sol2(2,-1);
realVec sol3(2,1);
realVec sol4(2,1);
pop.push_back( sol1 );
pop.push_back( sol2 );
pop.push_back( sol3 );
pop.push_back( sol4 );
// on the sphere function everyone has the same fitness of 1
if( test(pop, 0) != 0 ) {
exit(1);
}
pop.erase(pop.begin(),pop.end());
// fixed test
sol1 = realVec(2,0);
sol2 = realVec(2,0);
sol3 = realVec(2,1);
sol4 = realVec(2,1);
pop.push_back( sol1 );
pop.push_back( sol2 );
pop.push_back( sol3 );
pop.push_back( sol4 );
if( test(pop, 1) != 1 ) {
exit(1);
}
// test on a random normal distribution
eoNormalGenerator<double> normal(1,rng);
eoInitFixedLength<realVec> init_N(2, normal);
pop = eoPop<realVec>( 1000000, init_N );
double iqr = test(pop, 1.09);
if( iqr < 1.08 || iqr > 1.11 ) {
exit(1);
}
}

View file

@ -0,0 +1,68 @@
//-----------------------------------------------------------------------------
// t-eoInitPermutation.cpp
//-----------------------------------------------------------------------------
#include <eo>
#include <eoInt.h>
//-----------------------------------------------------------------------------
typedef eoInt<double> Chrom;
//-----------------------------------------------------------------------------
double real_value(const Chrom & _chrom)
{
double sum = 0;
for (unsigned i = 0; i < _chrom.size(); i++)
sum += _chrom[i];
return sum/_chrom.size();
}
// Return true if the given chromosome corresponds to a permutation
// There must be an nicer way to do it (set?) ...
bool check_permutation(const Chrom & _chrom)
{
for (unsigned i = 0; i < _chrom.size(); ++i)
for (unsigned j = 0; j < _chrom.size(); ++j)
if(i!=j)
if(_chrom[i]==_chrom[j]){
std::cout << " Error: Wrong permutation !" << std::endl;
std::string s;
s.append( " Wrong permutation in t-eoInitPermutation");
throw std::runtime_error( s );
}
return true;
}
int main()
{
const unsigned POP_SIZE = 8, CHROM_SIZE = 16;
unsigned i;
// a chromosome randomizer
eoInitPermutation <Chrom> random(CHROM_SIZE);
// the population:
eoPop<Chrom> pop;
// Evaluation
eoEvalFuncPtr<Chrom> eval( real_value );
for (i = 0; i < POP_SIZE; ++i)
{
Chrom chrom(CHROM_SIZE);
std::cout << " Initial chromosome n°" << i << " : " << chrom << "..." << std::endl;
random(chrom);
eval(chrom);
std::cout << " ... becomes : " << chrom << " after initialization" << std::endl;
check_permutation(chrom);
pop.push_back(chrom);
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,24 @@
//-----------------------------------------------------------------------------
// t-eoInt.cpp
//-----------------------------------------------------------------------------
#include <eo>
#include <eoInt.h>
//-----------------------------------------------------------------------------
typedef eoInt<double> Chrom;
//-----------------------------------------------------------------------------
int main()
{
Chrom chrom1, chrom2;
std::cout << "chrom1 = " << chrom1 << std::endl
<< "chrom2 = " << chrom2 << std::endl;
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,50 @@
//-----------------------------------------------------------------------------
// t-eoLogger.cpp
//-----------------------------------------------------------------------------
#include <eo>
//-----------------------------------------------------------------------------
int main(int ac, char** av)
{
eoParser parser(ac, av);
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(1);
}
make_help(parser);
make_verbose(parser);
eo::log << eo::setlevel(eo::debug);
eo::log << eo::warnings;
eo::log << "We are writing on the default output stream" << std::endl;
eo::log << eo::file("test.txt") << "In FILE" << std::endl;
eo::log << std::cout << "on COUT" << std::endl;
eo::log << eo::setlevel("errors");
eo::log << eo::setlevel(eo::errors);
eo::log << eo::quiet << "1) in quiet mode" << std::endl;
eo::log << eo::setlevel(eo::warnings) << eo::warnings << "2) in warnings mode" << std::endl;
eo::log << eo::setlevel(eo::logging);
eo::log << eo::errors;
eo::log << "3) in errors mode";
eo::log << std::endl;
eo::log << eo::debug << 4 << ')'
<< "4) in debug mode\n";
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,72 @@
//-----------------------------------------------------------------------------
// t-eoOrderXover.cpp
//-----------------------------------------------------------------------------
#include <set>
#include <eo>
#include <eoInt.h>
#include <eoOrderXover.h>
//-----------------------------------------------------------------------------
typedef eoInt<int> Chrom;
//-----------------------------------------------------------------------------
// Return true if the given chromosome corresponds to a permutation
bool check_permutation(const Chrom& _chrom){
unsigned size= _chrom.size();
std::set<unsigned> verif;
for(unsigned i=0; i< size; i++){
if(verif.insert(_chrom[i]).second==false){
std::cout << " Error: Wrong permutation !" << std::endl;
std::string s;
s.append( " Wrong permutation in t-eoShiftMutation");
throw std::runtime_error( s );
return false;
}
}
return true;
}
int main()
{
const unsigned POP_SIZE = 3, CHROM_SIZE = 8;
unsigned i;
// a chromosome randomizer
eoInitPermutation <Chrom> random(CHROM_SIZE);
// the population:
eoPop<Chrom> pop;
// Evaluation
//eoEvalFuncPtr<Chrom> eval( real_value );
for (i = 0; i < POP_SIZE; ++i)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
//eval(chrom);
pop.push_back(chrom);
}
// a shift mutation
eoOrderXover<Chrom> cross;
for (i = 0; i < POP_SIZE; ++i)
std::cout << " Initial chromosome n<>" << i << " : " << pop[i] << "..." << std::endl;
cross(pop[0],pop[1]);
cross(pop[1],pop[2]);
for (i = 0; i < POP_SIZE; ++i) {
std::cout << " Initial chromosome n<>" << i << " becomes : " << pop[i] << " after orderXover" << std::endl;
check_permutation(pop[i]);
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,148 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// t-eoPBIL.cpp
// (c) 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
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: Marc.Schoenauer@inria.fr
*/
//-----------------------------------------------------------------------------
/** test program for PBIL algorithm */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <eo>
#include <ga/make_ga.h>
#include "binary_value.h"
#include <apply.h>
#include <ga/eoPBILDistrib.h>
#include <ga/eoPBILOrg.h>
#include <ga/eoPBILAdditive.h>
#include <eoSimpleEDA.h>
using namespace std;
typedef eoBit<double> Indi;
// instanciating the outside subroutine that creates the distribution
#include "ga/make_PBILdistrib.h"
eoPBILDistrib<Indi> & make_PBILdistrib(eoParser& _parser, eoState&_state, Indi _eo)
{
return do_make_PBILdistrib(_parser, _state, _eo);
}
// instanciating the outside subroutine that creates the update rule
#include "ga/make_PBILupdate.h"
eoDistribUpdater<Indi> & make_PBILupdate(eoParser& _parser, eoState&_state, Indi _eo)
{
return do_make_PBILupdate(_parser, _state, _eo);
}
int main(int argc, char* argv[])
{
try
{
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
///// FIRST, problem or representation dependent stuff
//////////////////////////////////////////////////////
// The evaluation fn - encapsulated into an eval counter for output
eoEvalFuncPtr<Indi, double> mainEval( binary_value<Indi>);
eoEvalFuncCounter<Indi> eval(mainEval);
// Construction of the distribution
eoPBILDistrib<Indi> & distrib = make_PBILdistrib(parser, state, Indi());
// and the update rule
eoDistribUpdater<Indi> & update = make_PBILupdate(parser, state, Indi());
//// Now the representation-independent things
//////////////////////////////////////////////
// stopping criteria
eoContinue<Indi> & term = make_continue(parser, state, eval);
// output
eoCheckPoint<Indi> & checkpoint = make_checkpoint(parser, state, eval, term);
// add a graphical output for the distribution
// first, get the direname from the parser
// it has been enetered in make_checkoint
eoParam* ptParam = parser.getParamWithLongName(string("resDir"));
eoValueParam<string>* ptDirNameParam = dynamic_cast<eoValueParam<string>*>(ptParam);
if (!ptDirNameParam) // not found
throw runtime_error("Parameter resDir not found where it was supposed to be");
// now create the snapshot monitor
eoValueParam<bool>& plotDistribParam = parser.getORcreateParam(false, "plotDistrib",
"Plot Distribution", '\0',
"Output - Graphical");
if (plotDistribParam.value())
{
#ifdef HAVE_GNUPLOT
unsigned frequency=1; // frequency of plots updates
eoGnuplot1DSnapshot *distribSnapshot = new eoGnuplot1DSnapshot(ptDirNameParam->value(),
frequency, "distrib");
state.storeFunctor(distribSnapshot);
// add the distribution (it is an eoValueParam<vector<double> >)
distribSnapshot->add(distrib);
// and of course add it to the checkpoint
checkpoint.add(*distribSnapshot);
#endif
}
// the algorithm: EDA
// don't know where else to put the population size!
unsigned popSize = parser.getORcreateParam(unsigned(100), "popSize",
"Population Size", 'P', "Algorithm").value();
eoSimpleEDA<Indi> eda(update, eval, popSize, checkpoint);
///// End of construction of the algorith
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(parser);
//// GO
///////
eda(distrib); // run the eda
std::cout << "Final Distribution\n";
distrib.printOn(std::cout);
std::cout << std::endl;
// wait - for graphical output
if (plotDistribParam.value())
{
string foo;
cin >> foo;
}
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}

View file

@ -0,0 +1,56 @@
//-----------------------------------------------------------------------------
// t-eoParallel.cpp
//-----------------------------------------------------------------------------
#include <omp.h>
#include <eo>
#include <es/make_real.h>
//#include <apply.h>
#include "real_value.h"
//-----------------------------------------------------------------------------
typedef eoReal< eoMinimizingFitness > EOT;
int main(int ac, char** av)
{
eoParser parser(ac, av);
unsigned int popSize = parser.getORcreateParam((unsigned int)100, "popSize", "Population Size", 'P', "Evolution Engine").value();
unsigned int dimSize = parser.getORcreateParam((unsigned int)10, "dimSize", "Dimension Size", 'd', "Evolution Engine").value();
uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value();
if (seedParam == 0) { seedParam = time(0); }
make_parallel(parser);
make_help(parser);
rng.reseed( seedParam );
eoUniformGenerator< double > gen(-5, 5);
eoInitFixedLength< EOT > init( dimSize, gen );
eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value );
eoEvalFuncCounter< EOT > eval( mainEval );
eoPop< EOT > pop( popSize, init );
//apply< EOT >( eval, pop );
eoPopLoopEval< EOT > popEval( eval );
popEval( pop, pop );
eo::log << eo::quiet << "DONE!" << std::endl;
#pragma omp parallel
{
if ( 0 == omp_get_thread_num() )
{
eo::log << "num of threads: " << omp_get_num_threads() << std::endl;
}
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,31 @@
#include <iostream>
#include <eo>
int main(int ac, char** av)
{
eoParser parser(ac, av);
unsigned int alpha1 = parser.createParam(10, "alpha1", "Alpha parameter").value();
unsigned int alpha2 = parser.createParam(10, "alpha2", "Alpha parameter").value();
unsigned int alpha3 = parser.createParam(10, "alpha3", "Alpha parameter").value();
unsigned int alpha4 = parser.createParam(10, "alpha4", "Alpha parameter").value();
unsigned int alpha5 = parser.createParam(10, "alpha5", "Alpha parameter").value();
unsigned int alpha6 = parser.createParam(10, "alpha6", "Alpha parameter").value();
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(1);
}
make_help(parser);
std::cout << "alpha1: " << alpha1 << std::endl;
std::cout << "alpha2: " << alpha2 << std::endl;
std::cout << "alpha3: " << alpha3 << std::endl;
std::cout << "alpha4: " << alpha4 << std::endl;
std::cout << "alpha5: " << alpha5 << std::endl;
std::cout << "alpha6: " << alpha6 << std::endl;
return 0;
}

View file

@ -0,0 +1,53 @@
//-----------------------------------------------------------------------------
// t-rng.cpp
//-----------------------------------------------------------------------------
// This file really needs to be implementes usign some stringent tests, for now
// we simply check that the impementation of some methods does generally work...
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <eo>
#include <utils/eoRNG.h>
using namespace std;
int main()
{
const size_t num(10000);
double mean(100.);
double sigma(5.);
double sum(0.);
for(size_t i=0; i<num; ++i)
sum += abs(rng.normal(sigma));
sum /= double(num);
if(sum > sigma / 0.68) {
cerr << "Normal distribution seems out of bounds; "
<< "rerun to make sure it wasn't a statistical outlier" << endl;
return -1;
}
sum = 0.;
for(size_t i=0; i<num; ++i)
sum += abs(rng.normal(mean, sigma) - mean);
sum /= double(num);
if(sum > sigma / 0.68) {
cerr << "Normal distribution seems out of bounds; "
<< "rerun to make sure it wasn't a statistical outlier" << endl;
return -1;
}
return 0;
}
// Local Variables:
// coding: iso-8859-1
// mode: C++
// c-file-offsets: ((c . 0))
// c-file-style: "Stroustrup"
// fill-column: 80
// End:

View file

@ -0,0 +1,66 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
t-eoRandom.cpp
Test program for random generator
(c) GeNeura Team, 1999
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
/**
CVS Info: $Date: 2003-02-27 19:20:24 $ $Author: okoenig $ $Revision: 1.13 $
*/
//-----------------------------------------------------------------------------
#include <iostream> // cout
#include <fstream> // ostrstream, istrstream
#include <utils/eoRndGenerators.h> // eoBin
//#include <eoNormal.h>
//#include <eoNegExp.h>
//-----------------------------------------------------------------------------
int main() {
eoUniformGenerator<float> u1(-2.5,3.5);
eoUniformGenerator<double> u2(0.003, 0.05 );
eoUniformGenerator<unsigned long> u3( 10000U, 10000000U);
try
{ // throws an error
eoUniformGenerator<unsigned long> utest( 10000000U, 10000U);
throw; // if this succeeds something is wrong, make sure that that is noticed
}
catch (std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
std::ofstream os("t-eoRandom.out");
for ( unsigned i = 0; i < 100; i ++)
{
os << u1() << "\t" << u2() << "\t" << u3() << std::endl;
}
return 0; // to avoid VC++ complaints
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,72 @@
#include <iostream>
#include <es/make_real.h>
#include "real_value.h"
#include <apply.h>
using namespace std;
int main(int argc, char* argv[])
{
try
{
typedef eoReal<eoMinimizingFitness> EOT;
eoParser parser(argc, argv); // for user-parameter reading
eoState state; // keeps all things allocated
///// FIRST, problem or representation dependent stuff
//////////////////////////////////////////////////////
// The evaluation fn - encapsulated into an eval counter for output
eoEvalFuncPtr<EOT, double, const std::vector<double>&>
mainEval( real_value );
eoEvalFuncCounter<EOT> eval(mainEval);
// the genotype - through a genotype initializer
eoRealInitBounded<EOT>& init = make_genotype(parser, state, EOT());
// Build the variation operator (any seq/prop construct)
eoGenOp<EOT>& op = make_op(parser, state, init);
//// Now the representation-independent things
//////////////////////////////////////////////
// initialize the population - and evaluate
// yes, this is representation indepedent once you have an eoInit
eoPop<EOT>& pop = make_pop(parser, state, init);
// stopping criteria
eoContinue<EOT> & term = make_continue(parser, state, eval);
// output
eoCheckPoint<EOT> & checkpoint = make_checkpoint(parser, state, eval, term);
// algorithm (need the operator!)
eoAlgo<EOT>& ea = make_algo_scalar(parser, state, eval, checkpoint, op);
///// End of construction of the algorith
/////////////////////////////////////////
// to be called AFTER all parameters have been read!!!
make_help(parser);
//// GO
///////
// evaluate intial population AFTER help and status in case it takes time
apply<EOT>(eval, pop);
// print it out
std::cout << "Initial Population\n";
pop.sortedPrintOn(std::cout);
std::cout << std::endl;
run_ea(ea, pop); // run the ea
std::cout << "Final Population\n";
pop.sortedPrintOn(std::cout);
std::cout << std::endl;
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}

View file

@ -0,0 +1,223 @@
//-----------------------------------------------------------------------------
// to avoid long name warnings
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <stdexcept> // runtime_error
//-----------------------------------------------------------------------------
// tt.cpp:
//
//-----------------------------------------------------------------------------
// general
#include <eo>
//-----------------------------------------------------------------------------
struct Dummy : public EO<double>
{
typedef double Type;
void printOn(std::ostream & _os) const
{
_os << " - ";
EO<double>::printOn(_os);
}
};
struct eoDummyPop : public eoPop<Dummy>
{
public :
eoDummyPop(int s=0) { resize(s); }
};
//-----------------------------------------------------------------------------
int the_main(int argc, char **argv)
{
eoParser parser(argc, argv);
eoValueParam<unsigned int> parentSizeParam(10, "parentSize", "Parent size",'P');
parser.processParam( parentSizeParam );
unsigned int pSize = parentSizeParam.value();
eoValueParam<unsigned int> offsrpringSizeParam(10, "offsrpringSize", "Offsrpring size",'O');
parser.processParam( offsrpringSizeParam );
unsigned int oSize = offsrpringSizeParam.value();
eoValueParam<unsigned int> tournamentSizeParam(2, "tournamentSize", "Deterministic tournament size",'T');
parser.processParam( tournamentSizeParam );
unsigned int tSize = tournamentSizeParam.value();
eoValueParam<double> tournamentRateParam(0.75, "tournamentRate", "Stochastic tournament rate",'R');
parser.processParam( tournamentRateParam );
double tRate = tournamentRateParam.value();
eoValueParam<double> sParentsElitismRateParam(0.1, "sParentsElitismRateParam", "Strong elitism rate for parents",'E');
parser.processParam( sParentsElitismRateParam );
double sParentsElitismRate = sParentsElitismRateParam.value();
eoValueParam<double> sParentsEugenismRateParam(0, "sParentsEugenismRateParam", "Strong Eugenism rate",'e');
parser.processParam( sParentsEugenismRateParam );
double sParentsEugenismRate = sParentsEugenismRateParam.value();
eoValueParam<double> sOffspringElitismRateParam(0, "sOffspringElitismRateParam", "Strong elitism rate for parents",'E');
parser.processParam( sOffspringElitismRateParam );
double sOffspringElitismRate = sOffspringElitismRateParam.value();
eoValueParam<double> sOffspringEugenismRateParam(0, "sOffspringEugenismRateParam", "Strong Eugenism rate",'e');
parser.processParam( sOffspringEugenismRateParam );
double sOffspringEugenismRate = sOffspringEugenismRateParam.value();
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(1);
}
unsigned i;
std::cout << "Testing the replacements\nParents SIze = " << pSize
<< " and offspring size = " << oSize << std::endl;
rng.reseed(42);
eoDummyPop orgParents(pSize);
eoDummyPop orgOffspring(oSize);
// initialize so we can recognize them later!
for (i=0; i<pSize; i++)
orgParents[i].fitness(2*i+1);
for (i=0; i<oSize; i++)
orgOffspring[i].fitness(2*i);
std::cout << "Initial parents (odd)\n" << orgParents << "\n And initial offsprings (even)\n" << orgOffspring << std::endl;
// now the ones we're going to play with
eoDummyPop parents(0);
eoDummyPop offspring(0);
// the replacement procedures under test
eoGenerationalReplacement<Dummy> genReplace;
eoPlusReplacement<Dummy> plusReplace;
eoEPReplacement<Dummy> epReplace(tSize);
eoCommaReplacement<Dummy> commaReplace;
eoWeakElitistReplacement<Dummy> weakElitistReplace(commaReplace);
// the SSGA replacements
eoSSGAWorseReplacement<Dummy> ssgaWorseReplace;
eoSSGADetTournamentReplacement<Dummy> ssgaDTReplace(tSize);
eoSSGAStochTournamentReplacement<Dummy> ssgaDSReplace(tRate);
// here we go
// Generational
parents = orgParents;
offspring = orgOffspring;
std::cout << "eoGenerationalReplacement\n";
std::cout << "=========================\n";
genReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (orogonally even\n" << offspring << std::endl;
// Plus
parents = orgParents;
offspring = orgOffspring;
std::cout << "eoPlusReplacement\n";
std::cout << "=================\n";
plusReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl;
// EP (proche d'un PLUS
parents = orgParents;
offspring = orgOffspring;
std::cout << "eoEPReplacement\n";
std::cout << "===============\n";
epReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl;
// Comma
parents = orgParents;
offspring = orgOffspring;
if (parents.size() > offspring.size() )
std::cout << "Skipping Comma Replacement, more parents than offspring\n";
else
{
std::cout << "eoCommaReplacement\n";
std::cout << "==================\n";
commaReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl;
// Comma with weak elitism
parents = orgParents;
offspring = orgOffspring;
std::cout << "The same, with WEAK elitism\n";
std::cout << "===========================\n";
weakElitistReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl;
}
// preparing SSGA replace worse
parents = orgParents;
offspring = orgOffspring;
if (parents.size() < offspring.size() )
std::cout << "Skipping all SSGA Replacements, more offspring than parents\n";
else
{
std::cout << "SSGA replace worse\n";
std::cout << "==================\n";
ssgaWorseReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl;
// SSGA deterministic tournament
parents = orgParents;
offspring = orgOffspring;
std::cout << "SSGA deterministic tournament\n";
std::cout << "=============================\n";
ssgaDTReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl;
// SSGA stochastic tournament
parents = orgParents;
offspring = orgOffspring;
std::cout << "SSGA stochastic tournament\n";
std::cout << "==========================\n";
ssgaDTReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl;
}
// the general replacement
eoDeterministicSaDReplacement<Dummy> sAdReplace(sParentsElitismRate, sParentsEugenismRate, sOffspringElitismRate, sOffspringEugenismRate);// 10% parents survive
parents = orgParents;
offspring = orgOffspring;
std::cout << "General - strong elitism\n";
std::cout << "========================\n";
sAdReplace(parents, offspring);
std::cout << "Parents (originally odd)\n" << parents << "\n And offsprings (originally even)\n" << offspring << std::endl;
return 1;
}
int main(int argc, char **argv)
{
try
{
the_main(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
}

View file

@ -0,0 +1,67 @@
//-----------------------------------------------------------------------------
// t-eoRingTopology.cpp
//-----------------------------------------------------------------------------
#include <eo>
typedef eoRealParticle < double >Indi;
//Evaluation function
double f (const Indi & _indi)
{
double sum = 0;
for (unsigned i = 0; i < _indi.size (); i++)
sum += pow(_indi[i],2);
return (-sum);
}
int main_function(int argc, char **argv)
{
//Parameters
const unsigned int VEC_SIZE = 2;
const unsigned int POP_SIZE = 10;
const unsigned int NEIGHBORHOOD_SIZE= 3;
rng.reseed (33);
eoEvalFuncPtr<Indi, double, const Indi& > plainEval(f);
eoEvalFuncCounter < Indi > eval (plainEval);
eoUniformGenerator < double >uGen (0., 5.);
eoInitFixedLength < Indi > random (VEC_SIZE, uGen);
eoUniformGenerator < double >sGen (-1., 1.);
eoVelocityInitFixedLength < Indi > veloRandom (VEC_SIZE, sGen);
eoFirstIsBestInit < Indi > localInit;
eoPop < Indi > pop;
pop.append (POP_SIZE, random);
apply(eval, pop);
apply < Indi > (veloRandom, pop);
apply < Indi > (localInit, pop);
eoRingTopology<Indi> topology(NEIGHBORHOOD_SIZE);
topology.setup(pop);
std::cout<<"\n\n\nPopulation :\n\n"<<pop;
std::cout<<"\n\nNeighborhood :\n\n";
topology.printOn();
int k = NEIGHBORHOOD_SIZE/2;
for(unsigned i=0;i<pop.size();i++)
{
std::cout<<"\nBetween : ";
for(unsigned j=0;j<NEIGHBORHOOD_SIZE;j++)
std::cout<<"\n"<<pop[((pop.size()+i-k+j)%pop.size())];
std::cout<<"\nThe best is : \n"<<topology.best(i)<<"\n";
}
std::cout<<"\n\n";
return 1;
}
int main(int argc, char **argv)
{
try
{
main_function(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << " in t-eoRingTopology" << std::endl;
}
}

View file

@ -0,0 +1,66 @@
#include <eoPop.h>
#include <EO.h>
#include <eoProportionalSelect.h>
#include <eoStochasticUniversalSelect.h>
class TestEO : public EO<double> { public: unsigned index; };
using namespace std;
template <class Select>
int test_select()
{
vector<double> probs(4);
probs[0] = 0.1;
probs[1] = 0.4;
probs[2] = 0.2;
probs[3] = 0.3;
vector<double> counts(4,0.0);
// setup population
eoPop<TestEO> pop;
for (unsigned i = 0; i < probs.size(); ++i)
{
pop.push_back( TestEO());
pop.back().fitness( probs[i] * 2.1232 ); // some number to check scaling
pop.back().index = i;
}
Select select;
unsigned ndraws = 10000;
for (unsigned i = 0; i < ndraws; ++i)
{
const TestEO& eo = select(pop);
counts[eo.index]++;
}
cout << "Threshold = " << 1./sqrt(double(ndraws)) << endl;
for (unsigned i = 0; i < 4; ++i)
{
cout << counts[i]/ndraws << ' ';
double c = counts[i]/ndraws;
if (fabs(c - probs[i]) > 1./sqrt((double)ndraws)) {
cout << "ERROR" << endl;
return 1;
}
}
cout << endl;
return 0;
}
int main()
{
rng.reseed(44);
if (test_select<eoProportionalSelect<TestEO> >()) return 1;
return test_select<eoStochasticUniversalSelect<TestEO> >();
}

View file

@ -0,0 +1,117 @@
#include <eo>
// tests a Steady State GA
// Needed to define this breeder, maybe make it a breeder
template <class EOT>
class eoBreedOne : public eoBreed<EOT>
{
public :
eoBreedOne(eoSelectOne<EOT>& _select, eoGenOp<EOT>& _op) : select(_select), op(_op) {}
void operator()(const eoPop<EOT>& _src, eoPop<EOT>& _dest)
{
_dest.clear();
eoSelectivePopulator<EOT> pop(_src, _dest, select);
op(pop);
}
private :
eoSelectOne<EOT>& select;
eoGenOp<EOT>& op;
};
typedef eoMinimizingFitness FitnessType;
typedef eoVector<FitnessType, unsigned> EoType;
template <class EOT>
class eoMyEval : public eoEvalFunc<EOT>
{
public :
void operator()(EOT& _eo)
{
_eo.fitness(*std::max_element(_eo.begin(), _eo.end()));
}
};
template <class EOT>
class Xover : public eoBinOp<EOT>
{
bool operator()(EOT& _eo, const EOT& _eo2)
{
unsigned point = rng.random(_eo.size());
std::copy(_eo2.begin() + point, _eo2.end(), _eo.begin() + point);
return true;
}
};
template <class EOT>
class Mutate : public eoMonOp<EOT>
{
bool operator()(EOT& _eo)
{
unsigned point = rng.random(_eo.size());
_eo[point] = rng.random(1024);
return true;
}
};
int main()
{
int pop_size = 10;
eoGenContinue<EoType> cnt(10);
eoCheckPoint<EoType> cp(cnt);
Xover<EoType> xover;
Mutate<EoType> mutate;
eoProportionalOp<EoType> opsel;
opsel.add(xover, 0.8);
opsel.add(mutate, 0.2);
eoDetTournamentSelect<EoType> selector(3);
eoBreedOne<EoType> breed(selector, opsel);
// Replace a single one
eoSSGAWorseReplacement<EoType> replace;
// eoRandomSelect<EoType> selector;
// eoGeneralBreeder<EoType> breed(selector, opsel);
// eoPlusReplacement<EoType> replace;
eoMyEval<EoType> eval;
eoEasyEA<EoType> algo(cp, eval, breed, replace);
eoUniformGenerator<unsigned> unif(0,1024);
eoInitFixedLength<EoType> init(20, unif);
eoPop<EoType> pop(pop_size, init);
// evaluate
apply<EoType>(eval, pop);
eoBestFitnessStat<EoType> best("Best_Fitness");
eoAverageStat<EoType> avg("Avg_Fitness");
eoStdoutMonitor mon;
cp.add(best);
cp.add(avg);
// cp.add(mon);
mon.add(best);
mon.add(avg);
// and run
algo(pop);
}

View file

@ -0,0 +1,30 @@
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <time.h>
#include <eoSecondsElapsedContinue.h>
#include <eoPop.h>
#include <EO.h>
class Dummy : public EO<double> {};
int main() {
eoPop<Dummy> pop;
eoSecondsElapsedContinue<Dummy> cnt(1);
time_t start_time = time(0);
while (cnt(pop)) {}
time_t end_time = time(0);
int diff = end_time = start_time;
if (diff < 1) return 1;
return 0;
}

View file

@ -0,0 +1,222 @@
// to avoid long name warnings
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <cstring>
#include <stdexcept>
#include <eo>
//-----------------------------------------------------------------------------
struct Dummy : public EO<double>
{
typedef double Type;
void printOn(std::ostream & _os) const
{
_os << " - ";
EO<double>::printOn(_os);
}
};
bool operator==(const Dummy & _d1, const Dummy & _d2)
{
return _d1.fitness() == _d2.fitness();
}
struct eoDummyPop : public eoPop<Dummy>
{
public :
eoDummyPop(int s=0) { resize(s); }
};
// helper - DOES NOT WORK if different individuals have same fitness!!!
template <class EOT>
unsigned isInPop(EOT & _indi, eoPop<EOT> & _pop)
{
for (unsigned i=0; i<_pop.size(); i++)
if (_pop[i] == _indi)
return i;
return _pop.size();
}
unsigned int pSize; // global variable, bouh!
std::string fitnessType; // yes, a global variable :-)
eoDummyPop parentsOrg;
template <class EOT>
void testSelectMany(eoSelect<EOT> & _select, std::string _name)
{
unsigned i;
std::cout << "\n\n" << fitnessType + _name << std::endl;
std::cout << "===============\n";
eoDummyPop parents(parentsOrg);
eoDummyPop offspring(0);
// do the selection
_select(parents, offspring);
// compute stats
std::vector<unsigned> nb(parents.size(), 0);
for (i=0; i<offspring.size(); i++)
{
unsigned trouve = isInPop<Dummy>(offspring[i], parents);
if (trouve == parents.size()) // pas trouve
throw std::runtime_error("Pas trouve ds parents");
nb[trouve]++;
}
// dump to file so you can plot using gnuplot - dir name is hardcoded!
std::string fName = "ResSelect/" + fitnessType + _name + ".select";
std::ofstream os(fName.c_str());
for (i=0; i<parents.size(); i++)
{
std::cout << i << " -> " << ( (double)nb[i])/offspring.size() << std::endl;
os << i << " " << ( (double)nb[i])/offspring.size() << std::endl;
}
}
template <class EOT>
void testSelectOne(eoSelectOne<EOT> & _select, eoHowMany & _offspringRate,
eoHowMany & _fertileRate, std::string _name)
{
eoTruncatedSelectOne<EOT> truncSelect(_select, _fertileRate);
eoSelectMany<EOT> percSelect(truncSelect, _offspringRate);
testSelectMany<EOT>(percSelect, _name);
}
//-----------------------------------------------------------------------------
int the_main(int argc, char **argv)
{
eoParser parser(argc, argv);
eoValueParam<unsigned> parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P');
pSize = parentSizeParam.value(); // global variable
// eoValueParam<double> offsrpringRateParam = parser.createParam<double>(1.0, "offsrpringRate", "Offsrpring rate",'O');
// double oRate = offsrpringRateParam.value();
eoValueParam<eoHowMany> offsrpringRateParam = parser.createParam(eoHowMany(1.0), "offsrpringRate", "Offsrpring rate (% or absolute)",'O');
eoHowMany oRate = offsrpringRateParam.value();
eoValueParam<eoHowMany> fertileRateParam = parser.createParam(eoHowMany(1.0), "fertileRate", "Fertility rate (% or absolute)",'F');
eoHowMany fRate = fertileRateParam.value();
eoValueParam<unsigned> tournamentSizeParam = parser.createParam(unsigned(2), "tournamentSize", "Deterministic tournament size",'T');
unsigned int tSize = tournamentSizeParam.value();
eoValueParam<double> tournamentRateParam = parser.createParam(1.0, "tournamentRate", "Stochastic tournament rate",'t');
double tRate = tournamentRateParam.value();
eoValueParam<double> rankingPressureParam = parser.createParam(2.0, "rankingPressure", "Selective pressure for the ranking selection",'p');
double rankingPressure = rankingPressureParam.value();
eoValueParam<double> rankingExponentParam = parser.createParam(1.0, "rankingExponent", "Exponent for the ranking selection",'e');
double rankingExponent = rankingExponentParam.value();
eoValueParam<std::string> fitTypeParam = parser.createParam(std::string("linear"), "fitType", "Type of fitness (linear, exp, log, super",'f');
fitnessType = fitTypeParam.value();
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(0);
}
// hard-coded directory name ...
system("mkdir ResSelect");
std::cout << "Testing the Selections\nParents size = " << pSize
<< ", offspring rate = " << oRate;
std::cout << " and putting rsulting files in dir ResSelect" << std::endl;
// initialize parent population
parentsOrg.resize(pSize);
if (fitnessType == std::string("linear"))
for (unsigned i=0; i<pSize; i++)
parentsOrg[i].fitness(i);
else if (fitnessType == std::string("exp"))
for (unsigned i=0; i<pSize; i++)
parentsOrg[i].fitness(exp((double)i));
else if (fitnessType == std::string("log"))
for (unsigned i=0; i<pSize; i++)
parentsOrg[i].fitness(log(i+1.));
else if (fitnessType == std::string("super"))
{
for (unsigned i=0; i<pSize-1; i++)
parentsOrg[i].fitness(i);
parentsOrg[pSize-1].fitness(10*pSize);
}
else
throw std::runtime_error("Invalid fitness Type"+fitnessType);
std::cout << "Initial parents (odd)\n" << parentsOrg << std::endl;
// random seed
eoValueParam<uint32_t>& seedParam = parser.createParam(uint32_t(0), "seed",
"Random number seed", 'S');
if (seedParam.value() == 0)
seedParam.value() = time(0);
rng.reseed(seedParam.value());
char fileName[1024];
// the selection procedures under test
// eoDetSelect<Dummy> detSelect(oRate);
// testSelectMany(detSelect, "detSelect");
// Roulette
eoProportionalSelect<Dummy> propSelect;
testSelectOne<Dummy>(propSelect, oRate, fRate, "PropSelect");
// Linear ranking using the perf2Worth construct
eoRankingSelect<Dummy> newRankingSelect(rankingPressure);
sprintf(fileName,"LinRank_%g",rankingPressure);
testSelectOne<Dummy>(newRankingSelect, oRate, fRate, fileName);
// Exponential ranking using the perf2Worth construct
std::cout << "rankingExponent " << rankingExponent << std::endl;
eoRankingSelect<Dummy> expRankingSelect(rankingPressure,rankingExponent);
sprintf(fileName,"ExpRank_%g_%g",rankingPressure, rankingExponent);
testSelectOne<Dummy>(expRankingSelect, oRate, fRate, fileName);
// Det tournament
eoDetTournamentSelect<Dummy> detTourSelect(tSize);
sprintf(fileName,"DetTour_%d",tSize);
testSelectOne<Dummy>(detTourSelect, oRate, fRate, fileName);
// Stoch tournament
eoStochTournamentSelect<Dummy> stochTourSelect(tRate);
sprintf(fileName,"StochTour_%g",tRate);
testSelectOne<Dummy>(stochTourSelect, oRate, fRate, fileName);
// Fitness scaling
eoFitnessScalingSelect<Dummy> newFitScaleSelect(rankingPressure);
sprintf(fileName,"LinFitScale_%g",rankingPressure);
testSelectOne<Dummy>(newFitScaleSelect, oRate, fRate, fileName);
// Sequential selections
eoSequentialSelect<Dummy> seqSel(false);
strcpy(fileName,"Sequential");
testSelectOne<Dummy>(seqSel, oRate, fRate, fileName);
eoEliteSequentialSelect<Dummy> eliteSeqSel;
strcpy(fileName,"EliteSequential");
testSelectOne<Dummy>(eliteSeqSel, oRate, fRate, fileName);
return 1;
}
int main(int argc, char **argv)
{
try
{
the_main(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
return 1;
}
}

View file

@ -0,0 +1,240 @@
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// to avoid long name warnings
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
// general
#include <eo>
#include <utils/eoDistance.h>
//-----------------------------------------------------------------------------
struct Dummy : public EO<double>
{
typedef double Type;
void printOn(std::ostream & _os) const
{
EO<double>::printOn(_os);
std::cout << " " << xdist ;
}
double xdist;
};
class
eoDummyDistance : public eoDistance<Dummy>
{
double operator()(const Dummy & _v1, const Dummy & _v2)
{
double r= _v1.xdist - _v2.xdist;
return sqrt(r*r);
}
};
bool operator==(const Dummy & _d1, const Dummy & _d2)
{
return _d1.fitness() == _d2.fitness();
}
struct eoDummyPop : public eoPop<Dummy>
{
public :
eoDummyPop(int s=0) { resize(s); }
};
// helper - DOES NOT WORK if different individuals have same fitness!!!
template <class EOT>
unsigned isInPop(EOT & _indi, eoPop<EOT> & _pop)
{
for (unsigned i=0; i<_pop.size(); i++)
if (_pop[i] == _indi)
return i;
return _pop.size();
}
unsigned int pSize; // global variable, bouh!
std::string fitnessType; // yes, a global variable :-)
eoDummyPop parentsOrg;
template <class EOT>
void testSelectMany(eoSelect<EOT> & _select, std::string _name)
{
unsigned i;
std::cout << "\n\n" << fitnessType + _name << std::endl;
std::cout << "===============\n";
eoDummyPop parents(parentsOrg);
eoDummyPop offspring(0);
// do the selection
_select(parents, offspring);
// cout << "Pop offspring \n" << offspring << endl;
// compute stats
std::vector<unsigned> nb(parents.size(), 0);
for (i=0; i<offspring.size(); i++)
{
unsigned trouve = isInPop<Dummy>(offspring[i], parents);
if (trouve == parents.size()) // pas trouve
throw std::runtime_error("Pas trouve ds parents");
nb[trouve]++;
}
// dump to file so you can plot using gnuplot - dir name is hardcoded!
std::string fName = "ResSelect/" + fitnessType + _name + ".select";
std::ofstream os(fName.c_str());
for (i=0; i<parents.size(); i++)
{
std::cout << i << " -> " << ( (double)nb[i])/offspring.size() << std::endl;
os << i << " " << ( (double)nb[i])/offspring.size() << std::endl;
}
}
template <class EOT>
void testSelectOne(eoSelectOne<EOT> & _select, eoHowMany & _offspringRate,
eoHowMany & _fertileRate, std::string _name)
{
eoTruncatedSelectOne<EOT> truncSelect(_select, _fertileRate);
eoSelectMany<EOT> percSelect(truncSelect, _offspringRate);
testSelectMany<EOT>(percSelect, _name);
}
//-----------------------------------------------------------------------------
int the_main(int argc, char **argv)
{
eoParser parser(argc, argv);
// random seed
eoValueParam<uint32_t>& seedParam = parser.createParam(uint32_t(0), "seed", "Random number seed", 'S');
if (seedParam.value() == 0)
seedParam.value() = time(0);
rng.reseed(seedParam.value());
// pSize global variable !
eoValueParam<unsigned> pSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P');
pSize = pSizeParam.value();
eoHowMany oRate = parser.createParam(eoHowMany(1.0), "offsrpringRate", "Offsrpring rate (% or absolute)",'O').value();
eoHowMany fRate = parser.createParam(eoHowMany(1.0), "fertileRate", "Fertility rate (% or absolute)",'F').value();
double nicheSize = parser.createParam(0.1, "nicheSize", "Paramter Sigma for Sharing",'\0').value();
eoParamParamType & peakParam = parser.createParam(eoParamParamType("2(1,2)"), "peaks", "Description of the peaks: N(nb1,nb2,...,nbN)", 'p').value();
// the number of peaks: first item of the paramparam
unsigned peakNumber = atoi(peakParam.first.c_str());
if (peakNumber < 2)
{
std::cerr << "WARNING, nb of peaks must be larger than 2, using 2" << std::endl;
peakNumber = 2;
}
std::vector<unsigned> nbIndiPerPeak(peakNumber);
unsigned i, sum=0;
// the second item is a vector<string> containing all values
if (!peakParam.second.size()) // no other parameter : equal peaks
{
std::cerr << "WARNING, no nb of indis per peaks, using equal nbs" << std::endl;
for (i=0; i<peakNumber; i++)
nbIndiPerPeak[i] = pSize/peakNumber;
}
else // parameters passed by user
if (peakParam.second.size() != peakNumber)
{
std::cerr << "ERROR, not enough nb of indis per peaks" << std::endl;
exit(1);
}
else // now we have in peakParam.second all numbers
{
for (i=0; i<peakNumber; i++)
sum += ( nbIndiPerPeak[i] = atoi(peakParam.second[i].c_str()) );
// now normalize
for (i=0; i<peakNumber; i++)
nbIndiPerPeak[i] = nbIndiPerPeak[i] * pSize / sum;
}
// compute exact total
sum = 0;
for (i=0; i<peakNumber; i++)
sum += nbIndiPerPeak[i];
if (sum != pSize)
{
pSize = pSizeParam.value() = sum;
std::cerr << "WARNING, adjusting pSize to " << pSize << std::endl;
}
make_help(parser);
// hard-coded directory name ...
std::cout << "Testing the Sharing\n";
std::cout << " There will be " << peakNumber << " peaks";
std::cout << " with respective pops ";
for (i=0; i<peakNumber; i++)
std::cout << nbIndiPerPeak[i] << ", ";
std::cout << "\n Peaks are at distance 1 from one-another (dim 1),\n";
std::cout << " fitness of each peak is nb of peak, and\n";
std::cout << " fitness of individuals = uniform[fitness of peak +- 0.01]\n\n";
std::cout << "The resulting file (in dir ResSelect), contains \n";
std::cout << " the empirical proba. for each indi to be selected." << std::endl;
system("mkdir ResSelect");
// initialize parent population
parentsOrg.resize(pSize);
// all peaks of equal size in fitness, with different nn of individuals
unsigned index=0;
for (unsigned nbP=0; nbP<peakNumber; nbP++)
for (i=0; i<nbIndiPerPeak[nbP]; i++)
{
parentsOrg[index].fitness(nbP+1 + 0.02*eo::rng.uniform() - 0.01);
parentsOrg[index].xdist = nbP+1 + 0.02*eo::rng.uniform() - 0.01;
index++;
}
std::cout << "Initial population\n" << parentsOrg << std::endl;
char fileName[1024];
// the selection procedures under test
// eoDetSelect<Dummy> detSelect(oRate);
// testSelectMany(detSelect, "detSelect");
// Sharing using the perf2Worth construct
// need a distance for that
eoDummyDistance dist;
eoSharingSelect<Dummy> newSharingSelect(nicheSize, dist);
sprintf(fileName,"Niche_%g",nicheSize);
testSelectOne<Dummy>(newSharingSelect, oRate, fRate, fileName);
return 1;
}
int main(int argc, char **argv)
{
try
{
the_main(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
return 1;
}
}

View file

@ -0,0 +1,79 @@
//-----------------------------------------------------------------------------
// t-eoShiftMutation.cpp
//-----------------------------------------------------------------------------
#include <eo>
#include <eoInt.h>
#include <eoShiftMutation.h>
#include <set>
//-----------------------------------------------------------------------------
typedef eoInt<double> Chrom;
//-----------------------------------------------------------------------------
double real_value(const Chrom & _chrom)
{
double sum = 0;
for (unsigned i = 0; i < _chrom.size(); i++)
sum += _chrom[i];
return sum/_chrom.size();
}
// Return true if the given chromosome corresponds to a permutation
bool check_permutation(const Chrom& _chrom){
unsigned size= _chrom.size();
std::set<unsigned> verif;
for(unsigned i=0; i< size; i++){
if(verif.insert(_chrom[i]).second==false){
std::cout << " Error: Wrong permutation !" << std::endl;
std::string s;
s.append( " Wrong permutation in t-eoShiftMutation");
throw std::runtime_error( s );
return false;
}
}
return true;
}
int main()
{
const unsigned POP_SIZE = 3, CHROM_SIZE = 8;
unsigned i;
// a chromosome randomizer
eoInitPermutation <Chrom> random(CHROM_SIZE);
// the population:
eoPop<Chrom> pop;
// Evaluation
eoEvalFuncPtr<Chrom> eval( real_value );
for (i = 0; i < POP_SIZE; ++i)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
eval(chrom);
pop.push_back(chrom);
}
// a shift mutation
eoShiftMutation <Chrom> shift;
for (i = 0; i < POP_SIZE; ++i)
{
std::cout << " Initial chromosome n°" << i << " : " << pop[i] << "..." << std::endl;
shift(pop[i]);
std::cout << " ... becomes : " << pop[i] << " after shift mutation" << std::endl;
check_permutation(pop[i]);
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,139 @@
//-----------------------------------------------------------------------------
// to avoid long name warnings
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <stdexcept> // runtime_error
//-----------------------------------------------------------------------------
// tt.cpp:
//
//-----------------------------------------------------------------------------
// general
#include <utils/eoRNG.h> // Random number generators
#include <ga.h>
#include <utils/eoParser.h>
#include <utils/eoState.h>
//-----------------------------------------------------------------------------
// include package checkpointing
#include <utils/checkpointing>
// and provisions for Bounds reading
#include <utils/eoRealVectorBounds.h>
struct Dummy : public EO<double>
{
typedef double Type;
};
//-----------------------------------------------------------------------------
int the_main(int argc, char **argv)
{ // ok, we have a command line parser and a state
typedef eoBit<float> Chrom;
eoParser parser(argc, argv);
// Define Parameters
eoValueParam<unsigned int> dimParam((unsigned int)(5), "dimension", "dimension");
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<uint32_t> seed(time(0), "seed", "Random number seed");
// test if user entered or if default value used
if (parser.isItThere(seed))
std::cout << "YES\n";
else
std::cout << "NO\n";
eoValueParam<std::string> load_name("", "Load","Load",'L');
eoValueParam<std::string> save_name("", "Save","Save",'S');
// Register them
parser.processParam(dimParam, "Genetic Operators");
parser.processParam(rate, "Genetic Operators");
parser.processParam(factor, "Genetic Operators");
parser.processParam(load_name, "Persistence");
parser.processParam(save_name, "Persistence");
parser.processParam(seed, "Rng seeding");
// a bound param (need dim)
eoValueParam<eoRealVectorBounds> boundParam(eoRealVectorBounds(dimParam.value(),eoDummyRealNoBounds), "bounds","bounds",'b');
parser.processParam(boundParam, "Genetic Operators");
std::cout << "Bounds: " << boundParam.value() << std::endl;
eoState state;
state.registerObject(parser);
if (load_name.value() != "")
{ // 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);
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
return 0;
}
// Either load or initialize
if (load_name.value() != "")
{
state.load(load_name.value()); // load the rest
}
else
{
// else
// initialize rng and population
rng.reseed(seed.value());
}
// run the algorithm
// Save when needed
if (save_name.value() != "")
{
std::string file_name = save_name.value();
save_name.value() = ""; // so that it does not appear in the parser section of the state file
state.save(file_name);
}
for (int i = 0; i < 100; ++i)
rng.rand();
std::cout << "a random number is " << rng.random(1024) << std::endl;;
return 1;
}
int main(int argc, char **argv)
{
try
{
the_main(argc, argv);
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
}

View file

@ -0,0 +1,81 @@
//-----------------------------------------------------------------------------
// t-eoSwapMutation.cpp
//-----------------------------------------------------------------------------
#include <set>
#include <eo>
#include <eoInt.h>
#include <eoSwapMutation.h>
//-----------------------------------------------------------------------------
typedef eoInt<double> Chrom;
//-----------------------------------------------------------------------------
double real_value(const Chrom & _chrom)
{
double sum = 0;
for (unsigned i = 0; i < _chrom.size(); i++)
sum += _chrom[i];
return sum/_chrom.size();
}
//-----------------------------------------------------------------------------
// Return true if the given chromosome corresponds to a permutation
bool check_permutation(const Chrom& _chrom){
unsigned size= _chrom.size();
std::set<unsigned> verif;
for(unsigned i=0; i< size; i++){
if(verif.insert(_chrom[i]).second==false){
std::cout << " Error: Wrong permutation !" << std::endl;
std::string s;
s.append( " Wrong permutation in t-eoShiftMutation");
throw std::runtime_error( s );
return false;
}
}
return true;
}
int main()
{
const unsigned POP_SIZE = 8, CHROM_SIZE = 16;
unsigned i;
// a chromosome randomizer
eoInitPermutation <Chrom> random(CHROM_SIZE);
// the population:
eoPop<Chrom> pop;
// Evaluation
eoEvalFuncPtr<Chrom> eval( real_value );
for (i = 0; i < POP_SIZE; ++i)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
eval(chrom);
pop.push_back(chrom);
}
// a swap mutation
eoSwapMutation <Chrom> swap;
for (i = 0; i < POP_SIZE; ++i)
{
std::cout << " Initial chromosome n°" << i << " : " << pop[i] << "..." << std::endl;
swap(pop[i]);
std::cout << " ... becomes : " << pop[i] << " after swap mutation" << std::endl;
check_permutation(pop[i]);
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,299 @@
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <gp/eoParseTree.h>
#include <eo>
using namespace gp_parse_tree;
using namespace std;
//-----------------------------------------------------------------------------
class SymregNode
{
public :
enum Operator {X = 'x', Plus = '+', Min = '-', Mult = '*', PDiv = '/'};
SymregNode() { init(); }
SymregNode(Operator _op) { op = _op; }
virtual ~SymregNode() {}
// arity function, need this function!
int arity() const { return op == X? 0 : 2; }
void randomize() {}
// evaluation function, single case, using first argument to give value of variable
template <class Children>
void operator()(double& result, Children args, double var) const
{
double r1(0.), r2(0.);
if (arity() == 2)
{
args[0].apply(r1, var);
args[1].apply(r2, var);
}
switch (op)
{
case Plus : result = r1 + r2; break;
case Min : result = r1 - r2; break;
case Mult : result = r1 * r2; break;
case PDiv : {
if (r2 == 0.0)
// protection a la Koza, realistic implementations
// should maybe throw an exception
result = 1.0;
else
result = r1 / r2;
break;
}
case X : result = var; break;
}
}
/// 'Pretty' print to ostream function
template <class Children>
void operator()(string& result, Children args) const
{
static const string lb = "(";
static const string rb = ")";
char opStr[4] = " ";
opStr[1] = op;
if (arity() == 0)
{
result = "x";
return;
}
// else
string r1;
args[0].apply(r1);
result = lb + r1;
result += opStr;
args[1].apply(r1);
result += r1 + rb;
}
Operator getOp() const { return op; }
protected :
void init() { op = X; }
private :
Operator op; // the type of node
};
/// initializor
static SymregNode init_sequence[5] = {SymregNode::X, SymregNode::Plus, SymregNode::Min, SymregNode::Mult, SymregNode::PDiv}; // needed for intialization
// MSVC does not recognize the lt_arity<Node> in eoParseTreeDepthInit
// without this specialization ...
// 2 months later, it seems it does not accept this definition ...
// but dies accept the lt_arity<Node> in eoParseTreeDepthInit
// !!!
// #ifdef _MSC_VER
// template <>
// bool lt_arity(const SymregNode &node1, const SymregNode &node2)
// {
// return (node1.arity() < node2.arity());
// }
// #endif
//-----------------------------------------------------------
// saving, loading
std::ostream& operator<<(std::ostream& os, const SymregNode& eot)
{
os << static_cast<char>(eot.getOp());
return os;
}
std::istream& operator>>(std::istream& is, SymregNode& eot)
{
char type;
type = (char) is.get();
eot = SymregNode(static_cast<SymregNode::Operator>(type));
return is;
}
//-----------------------------------------------------------------------------
/** Implementation of a function evaluation object. */
double targetFunction(double x)
{
return x * x * x * x - x * x * x + x * x * x - x * x + x - 10;
}
// parameters controlling the sampling of points
const double xbegin = -10.0f;
const double xend = 10.0f;
const double xstep = 1.3f;
template <class FType, class Node> struct RMS: public eoEvalFunc< eoParseTree<FType, Node> >
{
public :
typedef eoParseTree<FType, Node> EoType;
typedef eoParseTree<FType, Node> argument_type;
typedef double fitness_type;
RMS() : eoEvalFunc<EoType>()
{
int n = int( (xend - xbegin) / xstep);
inputs.resize(n);
target.resize(n);
int i = 0;
for (double x = xbegin; x < xend && i < n; ++i, x+=xstep)
{
target[i] = targetFunction(x);
inputs[i] = x;
}
}
~RMS() {}
void operator()( EoType & _eo )
{
vector<double> outputs;
outputs.resize(inputs.size());
double fitness = 0.0;
for (unsigned i = 0; i < inputs.size(); ++i)
{
_eo.apply(outputs[i], inputs[i]);
fitness += (outputs[i] - target[i]) * (outputs[i] - target[i]);
}
fitness /= (double) target.size();
fitness = sqrt(fitness);
if (fitness > 1e+20)
fitness = 1e+20;
_eo.fitness(fitness);
}
private :
vector<double> inputs;
vector<double> target;
};
template <class EOT, class FitnessType>
void print_best(eoPop<EOT>& pop)
{
std::cout << std::endl;
FitnessType best = pop[0].fitness();
int index = 0;
for (unsigned i = 1; i < pop.size(); ++i)
{
if (best < pop[i].fitness())
{
best = pop[i].fitness();
index = i;
}
}
std::cout << "\t";
string str;
pop[index].apply(str);
std::cout << str.c_str();
std::cout << std::endl << "RMS Error = " << pop[index].fitness() << std::endl;
}
int main()
{
typedef eoMinimizingFitness FitnessType;
typedef SymregNode GpNode;
typedef eoParseTree<FitnessType, GpNode> EoType;
typedef eoPop<EoType> Pop;
const int MaxSize = 100;
const int nGenerations = 10; // only a test, so few generations
// Initializor sequence, contains the allowable nodes
vector<GpNode> init(init_sequence, init_sequence + 5);
// Depth Initializor, defaults to grow method.
eoGpDepthInitializer<FitnessType, GpNode> initializer(10, init);
// Root Mean Squared Error Measure
RMS<FitnessType, GpNode> eval;
Pop pop(50, initializer);
apply<EoType>(eval, pop);
eoSubtreeXOver<FitnessType, GpNode> xover(MaxSize);
eoBranchMutation<FitnessType, GpNode> mutation(initializer, MaxSize);
// The operators are encapsulated into an eoTRansform object,
// that performs sequentially crossover and mutation
eoSGATransform<EoType> transform(xover, 0.75, mutation, 0.25);
// The robust tournament selection
eoDetTournamentSelect<EoType> selectOne(2); // tSize in [2,POPSIZE]
// is now encapsulated in a eoSelectMany: 2 at a time -> SteadyState
eoSelectMany<EoType> select(selectOne,2, eo_is_an_integer);
// and the Steady-State replacement
eoSSGAWorseReplacement<EoType> replace;
// Terminators
eoGenContinue<EoType> term(nGenerations);
eoCheckPoint<EoType> checkPoint(term);
eoAverageStat<EoType> avg;
eoBestFitnessStat<EoType> best;
eoStdoutMonitor monitor;
checkPoint.add(monitor);
checkPoint.add(avg);
checkPoint.add(best);
monitor.add(avg);
monitor.add(best);
// GP generation
eoEasyEA<EoType> gp(checkPoint, eval, select, transform, replace);
std::cout << "Initialization done" << std::endl;
print_best<EoType, FitnessType>(pop);
try
{
gp(pop);
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
print_best<EoType, FitnessType>(pop);
}
// Local Variables:
// coding: iso-8859-1
// mode: C++
// c-file-offsets: ((c . 0))
// c-file-style: "Stroustrup"
// fill-column: 80
// End:

View file

@ -0,0 +1,104 @@
//-----------------------------------------------------------------------------
// t-eoEasySyncPSO.cpp
//-----------------------------------------------------------------------------
#ifndef __GNUG__
// to avoid long name warnings
#pragma warning(disable:4786)
#endif // __GNUG__
#include <eo>
//-----------------------------------------------------------------------------
typedef eoMinimizingFitness FitT;
typedef eoRealParticle < FitT > Particle;
//-----------------------------------------------------------------------------
// the objective function
double real_value (const Particle & _particle)
{
double sum = 0;
for (unsigned i = 0; i < _particle.size ()-1; i++)
sum += pow(_particle[i],2);
return (sum);
}
int main()
{
const unsigned int VEC_SIZE = 2;
const unsigned int POP_SIZE = 20;
const unsigned int NEIGHBORHOOD_SIZE= 5;
unsigned i;
// the population:
eoPop<Particle> pop;
// Evaluation
eoEvalFuncPtr<Particle, double, const Particle& > eval( real_value );
// position init
eoUniformGenerator < double >uGen (-3, 3);
eoInitFixedLength < Particle > random (VEC_SIZE, uGen);
// velocity init
eoUniformGenerator < double >sGen (-2, 2);
eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen);
// local best init
eoFirstIsBestInit < Particle > localInit;
// perform position initialization
pop.append (POP_SIZE, random);
// topology
eoLinearTopology<Particle> topology(NEIGHBORHOOD_SIZE);
// the full initializer
eoInitializer <Particle> init(eval,veloRandom,localInit,topology,pop);
init();
// bounds
eoRealVectorBounds bnds(VEC_SIZE,-1.5,1.5);
// velocity
eoStandardVelocity <Particle> velocity (topology,1,1.6,2,bnds);
// flight
eoStandardFlight <Particle> flight;
// Terminators
eoGenContinue <Particle> genCont1 (50);
eoGenContinue <Particle> genCont2 (50);
// PS flight
eoSyncEasyPSO<Particle> pso1(genCont1, eval, velocity, flight);
eoSyncEasyPSO<Particle> pso2(init,genCont2, eval, velocity, flight);
// flight
try
{
pso1(pop);
std::cout << "FINAL POPULATION AFTER SYNC PSO n°1:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
pso2(pop);
std::cout << "FINAL POPULATION AFTER SYNC PSO n°2:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,80 @@
//-----------------------------------------------------------------------------
// t-eoTwoOptMutation.cpp
//-----------------------------------------------------------------------------
#include <set>
#include <eo>
#include <eoInt.h>
#include <eoTwoOptMutation.h>
//-----------------------------------------------------------------------------
typedef eoInt<double> Chrom;
//-----------------------------------------------------------------------------
double real_value(const Chrom & _chrom)
{
double sum = 0;
for (unsigned i = 0; i < _chrom.size(); i++)
sum += _chrom[i];
return sum/_chrom.size();
}
//-----------------------------------------------------------------------------
// Return true if the given chromosome corresponds to a permutation
bool check_permutation(const Chrom& _chrom){
unsigned size= _chrom.size();
std::set<unsigned> verif;
for(unsigned i=0; i< size; i++){
if(verif.insert(_chrom[i]).second==false){
std::cout << " Error: Wrong permutation !" << std::endl;
std::string s;
s.append( " Wrong permutation in t-eoShiftMutation");
throw std::runtime_error( s );
return false;
}
}
return true;
}
int main()
{
const unsigned POP_SIZE = 3, CHROM_SIZE = 8;
unsigned i;
// a chromosome randomizer
eoInitPermutation <Chrom> random(CHROM_SIZE);
// the population:
eoPop<Chrom> pop;
// Evaluation
eoEvalFuncPtr<Chrom> eval( real_value );
for (i = 0; i < POP_SIZE; ++i)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
eval(chrom);
pop.push_back(chrom);
}
// a twoOpt mutation
eoTwoOptMutation <Chrom> twoOpt;
for (i = 0; i < POP_SIZE; ++i)
{
std::cout << " Initial chromosome n°" << i << " : " << pop[i] << "..." << std::endl;
twoOpt(pop[i]);
std::cout << " ... becomes : " << pop[i] << " after twoOpt mutation" << std::endl;
check_permutation(pop[i]);
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,22 @@
//-----------------------------------------------------------------------------
// t-eouniform
//-----------------------------------------------------------------------------
#include <iostream> // std::cout
#include <strstream> // ostrstream, istrstream
#include <eoUniform.h> // eoBin
//-----------------------------------------------------------------------------
main() {
eoUniform<float> u1(-2.5,3.5);
eoUniform<double> u2(0.003, 0 );
eoUniform<unsigned long> u3( 10000U, 10000000U);
std::cout << "u1\t\tu2\t\tu3" << std::endl;
for ( unsigned i = 0; i < 100; i ++) {
std::cout << u1() << "\t" << u2() << "\t" << u3() << std::endl;
}
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,74 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
t-eoVector.cpp
This program tests vector-like chromosomes
(c) GeNeura Team, 1999, 2000
Modified by Maarten Keijzer 2001
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cassert>
#include <iostream>
#include <utils/eoRndGenerators.h>
#include <eoVector.h> // eoVector
#include <eoInit.h>
#include <eoScalarFitness.h>
//-----------------------------------------------------------------------------
typedef eoVector<eoMaximizingFitness, int> Chrom1;
typedef eoVector<eoMinimizingFitness, int> Chrom2;
//-----------------------------------------------------------------------------
int main()
{
const unsigned SIZE = 4;
// check if the appropriate ctor gets called
Chrom1 chrom(SIZE, 5);
for (unsigned i = 0; i < chrom.size(); ++i)
{
assert(chrom[i] == 5);
}
eoUniformGenerator<Chrom1::AtomType> uniform(-1,1);
eoInitFixedLength<Chrom1> init(SIZE, uniform);
init(chrom);
std::cout << chrom << std::endl;
Chrom2 chrom2(chrom);
std::cout << chrom2 << std::endl;
// eoInitVariableLength<Chrom1> initvar(
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,76 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
t-eoVirus.cpp
This program tests the the binary cromosomes and several genetic operators
(c) GeNeura Team, 1999
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#include <iostream> // std::cout
#include <eo> // general EO
#include "MGE/VirusOp.h"
#include "MGE/eoVirus.h"
#include "MGE/eoInitVirus.h"
#include <utils/eoRndGenerators.h>
#include "binary_value.h"
//-----------------------------------------------------------------------------
typedef eoVirus<float> Chrom;
//-----------------------------------------------------------------------------
int main()
{
const unsigned SIZE = 8;
eoBooleanGenerator gen;
eo::rng.reseed( time( 0 ) );
Chrom chrom(SIZE), chrom2(SIZE);
chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2));
std::cout << chrom << std::endl;
std::cout << chrom2 << std::endl;
// Virus Mutation
VirusBitFlip<float> vf;
unsigned i;
for ( i = 0; i < 10; i++ ) {
vf( chrom );
std::cout << chrom << std::endl;
}
// Chrom Mutation
std::cout << "Chrom mutation--------" << std::endl;
VirusMutation<float> vm;
for ( i = 0; i < 10; i++ ) {
vm( chrom );
std::cout << chrom << std::endl;
}
// Chrom Transmision
std::cout << "Chrom transmission--------" << std::endl;
VirusTransmission<float> vt;
vt( chrom2, chrom );
std::cout << chrom2 << std::endl;
return 0;
}

View file

@ -0,0 +1,218 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
t-eobin.cpp
This program tests the the binary cromosomes and several genetic operators
(c) GeNeura Team, 1999
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream> // std::cout
#include <sstream>
#include <eo> // general EO
#include <ga.h> // bitstring representation & operators
#include <utils/eoRndGenerators.h>
#include "binary_value.h"
//-----------------------------------------------------------------------------
typedef eoBit<double> Chrom;
//-----------------------------------------------------------------------------
void main_function()
{
const unsigned SIZE = 8;
unsigned i, j;
eoBooleanGenerator gen;
Chrom chrom(SIZE), chrom2;
chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2));
std::cout << "chrom: " << chrom << std::endl;
chrom[0] = chrom[SIZE - 1] = true; chrom.fitness(binary_value(chrom));
std::cout << "chrom: " << chrom << std::endl;
chrom[0] = chrom[SIZE - 1] = false; chrom.fitness(binary_value(chrom));
std::cout << "chrom: " << chrom << std::endl;
chrom[0] = chrom[SIZE - 1] = true; chrom.fitness(binary_value(chrom));
std::cout << "chrom.className() = " << chrom.className() << std::endl;
std::cout << "chrom: " << chrom << std::endl
<< "chrom2: " << chrom2 << std::endl;
std::ostringstream os;
os << chrom;
std::istringstream is(os.str());
is >> chrom2; chrom.fitness(binary_value(chrom2));
std::cout << "\nTesting reading, writing\n";
std::cout << "chrom: " << chrom << "\nchrom2: " << chrom2 << '\n';
std::fill(chrom.begin(), chrom.end(), false);
std::cout << "--------------------------------------------------"
<< std::endl << "eoMonOp's aplied to .......... " << chrom << std::endl;
eoInitFixedLength<Chrom>
random(chrom.size(), gen);
random(chrom); chrom.fitness(binary_value(chrom));
std::cout << "after eoBinRandom ............ " << chrom << std::endl;
eoOneBitFlip<Chrom> bitflip;
bitflip(chrom); chrom.fitness(binary_value(chrom));
std::cout << "after eoBitFlip .............. " << chrom << std::endl;
eoBitMutation<Chrom> mutation(0.5);
mutation(chrom); chrom.fitness(binary_value(chrom));
std::cout << "after eoBinMutation(0.5) ..... " << chrom << std::endl;
eoBitInversion<Chrom> inversion;
inversion(chrom); chrom.fitness(binary_value(chrom));
std::cout << "after eoBinInversion ......... " << chrom << std::endl;
eoBitNext<Chrom> next;
next(chrom); chrom.fitness(binary_value(chrom));
std::cout << "after eoBinNext .............. " << chrom << std::endl;
eoBitPrev<Chrom> prev;
prev(chrom); chrom.fitness(binary_value(chrom));
std::cout << "after eoBinPrev .............. " << chrom << std::endl;
std::fill(chrom.begin(), chrom.end(), false); chrom.fitness(binary_value(chrom));
std::fill(chrom2.begin(), chrom2.end(), true); chrom2.fitness(binary_value(chrom2));
std::cout << "--------------------------------------------------"
<< std::endl << "eoBinOp's aplied to ... "
<< chrom << " " << chrom2 << std::endl;
eo1PtBitXover<Chrom> xover;
std::fill(chrom.begin(), chrom.end(), false);
std::fill(chrom2.begin(), chrom2.end(), true);
xover(chrom, chrom2);
chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2));
std::cout << "eoBinCrossover ........ " << chrom << " " << chrom2 << std::endl;
for (i = 1; i < SIZE; i++)
{
eoNPtsBitXover<Chrom> nxover(i);
std::fill(chrom.begin(), chrom.end(), false);
std::fill(chrom2.begin(), chrom2.end(), true);
nxover(chrom, chrom2);
chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2));
std::cout << "eoBinNxOver(" << i << ") ........ "
<< chrom << " " << chrom2 << std::endl;
}
for (i = 1; i < SIZE / 2; i++)
for (j = 1; j < SIZE / 2; j++)
{
eoBitGxOver<Chrom> gxover(i, j);
std::fill(chrom.begin(), chrom.end(), false);
std::fill(chrom2.begin(), chrom2.end(), true);
gxover(chrom, chrom2);
chrom.fitness(binary_value(chrom)); chrom2.fitness(binary_value(chrom2));
std::cout << "eoBinGxOver(" << i << ", " << j << ") ..... "
<< chrom << " " << chrom2 << std::endl;
}
// test SGA algorithm
eoGenContinue<Chrom> continuator1(50);
eoFitContinue<Chrom> continuator2(65535.f);
eoCombinedContinue<Chrom> continuator(continuator1, continuator2);
eoCheckPoint<Chrom> checkpoint(continuator);
eoStdoutMonitor monitor;
checkpoint.add(monitor);
eoSecondMomentStats<Chrom> stats;
monitor.add(stats);
checkpoint.add(stats);
eoProportionalSelect<Chrom> select;
eoEvalFuncPtr<Chrom> eval(binary_value);
eoSGA<Chrom> sga(select, xover, 0.8f, bitflip, 0.1f, eval, checkpoint);
eoInitFixedLength<Chrom> init(16, gen);
eoPop<Chrom> pop(100, init);
apply<Chrom>(eval, pop);
sga(pop);
pop.sort();
std::cout << "Population " << pop << std::endl;
std::cout << "\nBest: " << pop[0].fitness() << '\n';
/*
Commented this out, waiting for a definite decision what to do with the mOp's
// Check multiOps
eoMultiMonOp<Chrom> mOp( &next );
mOp.adOp( &bitflip );
std::cout << "before multiMonOp............ " << chrom << std::endl;
mOp( chrom );
std::cout << "after multiMonOp .............. " << chrom << std::endl;
eoBinGxOver<Chrom> gxover(2, 4);
eoMultiBinOp<Chrom> mbOp( &gxover );
mOp.adOp( &bitflip );
std::cout << "before multiBinOp............ " << chrom << " " << chrom2 << std::endl;
mbOp( chrom, chrom2 );
std::cout << "after multiBinOp .............. " << chrom << " " << chrom2 <<std::endl;
*/
}
//-----------------------------------------------------------------------------
// For MSVC memory lead detection
#ifdef _MSC_VER
#include <crtdbg.h>
#endif
int main()
{
#ifdef _MSC_VER
// rng.reseed(42);
int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
flag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(flag);
// _CrtSetBreakAlloc(100);
#endif
try
{
main_function();
}
catch(std::exception& e)
{
std::cout << "Exception: " << e.what() << '\n';
}
}

View file

@ -0,0 +1,89 @@
//-----------------------------------------------------------------------------
// t-eofitness.cpp
// (c) GeNeura Team 1998
//-----------------------------------------------------------------------------
#include <time.h> // time
#include <stdlib.h> // srand, rand
#include <iostream> // std::cout
#include <eoScalarFitness.h>
using namespace std;
//-----------------------------------------------------------------------------
template <class Fitness>
int test_fitness(Fitness a, Fitness b)
{
// srand(time(0));
// Fitness a = aval; //static_cast<double>(rand()) / RAND_MAX;
// Fitness b = bval; //static_cast<double>(rand()) / RAND_MAX;
std::cout.precision(2);
unsigned repeat = 2;
while (repeat--)
{
std::cout << "------------------------------------------------------" << std::endl;
std::cout << "testing < ";
if (a < b)
std::cout << a << " < " << b << " is true" << std::endl;
else
std::cout << a << " < " << b << " is false" <<std::endl;
std::cout << "testing > ";
if (a > b)
std::cout << a << " > " << b << " is true" << std::endl;
else
std::cout << a << " > " << b << " is false" <<std::endl;
std::cout << "testing == ";
if (a == b)
std::cout << a << " == " << b << " is true" << std::endl;
else
std::cout << a << " == " << b << " is false" <<std::endl;
std::cout << "testing != ";
if (a != b)
std::cout << a << " != " << b << " is true" << std::endl;
else
std::cout << a << " != " << b << " is false" <<std::endl;
a = b;
}
return 1;
}
int main()
{
std::cout << "Testing minimizing fitness with 1 and 2" << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
eoMinimizingFitness a = 1;
eoMinimizingFitness b = 2;
test_fitness(a, b);
std::cout << "Testing minimizing fitness with 2 and 1" << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
test_fitness(b, a);
std::cout << "Testing maximizing fitness with 1 and 2" << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
eoMaximizingFitness a1 = 1;
eoMaximizingFitness b1 = 2;
test_fitness(a1,b1);
std::cout << "Testing maximizing fitness with 2 and 1" << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
test_fitness(b1,a1);
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,224 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
/*
(c) Thales group, 2010
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation;
version 2 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: http://eodev.sourceforge.net
Authors:
Caner Candan <caner.candan@thalesgroup.com>
*/
//-----------------------------------------------------------------------------
// t-openmp.cpp
//-----------------------------------------------------------------------------
#include <fstream>
#include <sstream>
#include <climits>
#include <eo>
#include <es/make_real.h>
#include <apply.h>
#include <omp.h>
#include <unistd.h>
#include "real_value.h"
//-----------------------------------------------------------------------------
typedef eoReal< eoMinimizingFitness > EOT;
//-----------------------------------------------------------------------------
inline uint32_t get_rdtsc() { __asm__ ("xor %eax, %eax; cpuid; rdtsc"); }
double variable_time_function(const std::vector<double>&)
{
eoRng myrng( get_rdtsc() );
::usleep( myrng.random( 10 ) );
return 0.0;
}
double measure_apply( size_t p,
void (*fct)(eoUF<EOT&, void>&, std::vector<EOT>&),
eoInitFixedLength< EOT >& init,
eoEvalFuncCounter< EOT >& eval )
{
eoPop< EOT > pop( p, init );
double t1 = omp_get_wtime();
fct( eval, pop );
double t2 = omp_get_wtime();
return t2 - t1;
}
void measure( size_t p,
eoInitFixedLength< EOT >& init,
eoEvalFuncCounter< EOT >& eval,
std::ofstream& speedupFile,
std::ofstream& efficiencyFile,
std::ofstream& dynamicityFile,
size_t nbtask )
{
// sequential scope
double Ts = measure_apply( p, apply< EOT >, init, eval );
// parallel scope
double Tp = measure_apply( p, omp_apply< EOT >, init, eval );
// parallel scope dynamic
double Tpd = measure_apply( p, omp_dynamic_apply< EOT >, init, eval );
double speedup = Ts / Tp;
if ( speedup > nbtask ) { return; }
double efficiency = speedup / nbtask;
speedupFile << speedup << ' ';
efficiencyFile << efficiency << ' ';
eo::log << eo::debug;
eo::log << "Ts = " << Ts << std::endl;
eo::log << "Tp = " << Tp << std::endl;
eo::log << "S_p = " << speedup << std::endl;
eo::log << "E_p = " << efficiency << std::endl;
double dynamicity = Tp / Tpd;
if ( dynamicity > nbtask ) { return; }
eo::log << "Tpd = " << Tpd << std::endl;
eo::log << "D_p = " << dynamicity << std::endl;
dynamicityFile << dynamicity << ' ';
}
int main(int ac, char** av)
{
eoParser parser(ac, av);
unsigned int popMin = parser.getORcreateParam((unsigned int)1, "popMin", "Population Min", 'p', "Evolution Engine").value();
unsigned int popStep = parser.getORcreateParam((unsigned int)1, "popStep", "Population Step", 0, "Evolution Engine").value();
unsigned int popMax = parser.getORcreateParam((unsigned int)100, "popMax", "Population Max", 'P', "Evolution Engine").value();
unsigned int dimMin = parser.getORcreateParam((unsigned int)1, "dimMin", "Dimension Min", 'd', "Evolution Engine").value();
unsigned int dimStep = parser.getORcreateParam((unsigned int)1, "dimStep", "Dimension Step", 0, "Evolution Engine").value();
unsigned int dimMax = parser.getORcreateParam((unsigned int)100, "dimMax", "Dimension Max", 'D', "Evolution Engine").value();
unsigned int nRun = parser.getORcreateParam((unsigned int)100, "nRun", "Number of runs", 'r', "Evolution Engine").value();
std::string fileNamesPrefix = parser.getORcreateParam(std::string(""), "fileNamesPrefix", "Prefix of all results files name", 'H', "Results").value();
std::string speedupFileName = parser.getORcreateParam(std::string("speedup"), "speedupFileName", "Speedup file name", 0, "Results").value();
std::string efficiencyFileName = parser.getORcreateParam(std::string("efficiency"), "efficiencyFileName", "Efficiency file name", 0, "Results").value();
std::string dynamicityFileName = parser.getORcreateParam(std::string("dynamicity"), "dynamicityFileName", "Dynamicity file name", 0, "Results").value();
uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value();
if (seedParam == 0) { seedParam = time(0); }
unsigned int measureConstTime = parser.getORcreateParam((unsigned int)1, "measureConstTime", "Toggle measure of constant time", 'C', "Results").value();
unsigned int measureVarTime = parser.getORcreateParam((unsigned int)1, "measureVarTime", "Toggle measure of variable time", 'V', "Results").value();
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
exit(1);
}
make_help(parser);
make_verbose(parser);
rng.reseed( seedParam );
eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value );
eoEvalFuncCounter< EOT > eval( mainEval );
eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval_variable( variable_time_function );
eoEvalFuncCounter< EOT > eval_variable( mainEval_variable );
eoUniformGenerator< double > gen(-5, 5);
std::ostringstream params;
params << "_p" << popMin << "_pS" << popStep << "_P" << popMax
<< "_d" << dimMin << "_dS" << dimStep << "_D" << dimMax
<< "_r" << nRun << "_s" << seedParam;
std::ofstream speedupFile( std::string( fileNamesPrefix + speedupFileName + params.str() ).c_str() );
std::ofstream efficiencyFile( std::string( fileNamesPrefix + efficiencyFileName + params.str() ).c_str() );
std::ofstream dynamicityFile( std::string( fileNamesPrefix + dynamicityFileName + params.str() ).c_str() );
std::ofstream speedupFile_variable( std::string( fileNamesPrefix + "variable_" + speedupFileName + params.str() ).c_str() );
std::ofstream efficiencyFile_variable( std::string( fileNamesPrefix + "variable_" + efficiencyFileName + params.str() ).c_str() );
std::ofstream dynamicityFile_variable( std::string( fileNamesPrefix + "variable_" + dynamicityFileName + params.str() ).c_str() );
size_t nbtask = 1;
#pragma omp parallel
{
nbtask = omp_get_num_threads();
}
eo::log << eo::logging << "Nb task: " << nbtask << std::endl;
for ( size_t p = popMin; p <= popMax; p += popStep )
{
for ( size_t d = dimMin; d <= dimMax; d += dimStep )
{
eo::log << eo::logging << p << 'x' << d << std::endl;
for ( size_t r = 0; r < nRun; ++r )
{
eoInitFixedLength< EOT > init( d, gen );
// for constant time measure
if ( measureConstTime == 1 )
{
measure( p, init, eval, speedupFile, efficiencyFile, dynamicityFile, nbtask );
}
// for variable time measure
if ( measureVarTime == 1 )
{
measure( p, init, eval_variable, speedupFile_variable, efficiencyFile_variable, dynamicityFile_variable, nbtask );
}
} // end of runs
if ( measureConstTime == 1 )
{
speedupFile << std::endl;
efficiencyFile << std::endl;
dynamicityFile << std::endl;
}
if ( measureVarTime == 1 )
{
speedupFile_variable << std::endl;
efficiencyFile_variable << std::endl;
dynamicityFile_variable << std::endl;
}
} // end of dimension
} // end of population
return 0;
}
//-----------------------------------------------------------------------------

161
deprecated/eo/test/t-openmp.py Executable file
View file

@ -0,0 +1,161 @@
#!/usr/bin/env python
#
# (c) Thales group, 2010
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;
# version 2 of the License.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Contact: http://eodev.sourceforge.net
#
# Authors:
# Caner Candan <caner.candan@thalesgroup.com>
#
import optparse, logging, sys, os
from datetime import datetime
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
LOG_DEFAULT_FILENAME='notitle.log'
RESULT_FILE_FORMAT='%s%s_p%d_pS%d_P%d_d%d_dS%d_D%d_r%d_s%d'
def parser(parser=optparse.OptionParser()):
# general parameters
parser.add_option('-v', '--verbose', choices=LEVELS.keys(), default='info', help='set a verbose level')
parser.add_option('-f', '--file', help='give an input project filename', default='')
parser.add_option('-o', '--output', help='give an output filename for logging', default=LOG_DEFAULT_FILENAME)
# general parameters ends
parser.add_option('-r', '--nRun', type='int', default=100, help='how many times you would compute each iteration ?')
parser.add_option('-s', '--seed', type='int', default=1, help='give here a seed value')
parser.add_option('-n', '--nProc', type='int', default=1, help='give a number of processus, this value is multiplied by the measures bounds')
parser.add_option('-F', '--fixedBound', type='int', default=1000, help='give the fixed bound value common for all measures')
topic = str(datetime.today())
for char in [' ', ':', '-', '.']: topic = topic.replace(char, '_')
parser.add_option('-t', '--topic', default='openmp_measures_' + topic + '/', help='give here a topic name used to create the folder')
parser.add_option('-E', '--onlyexecute', action='store_true', default=False, help='used this option if you only want to execute measures without generating images')
parser.add_option('-X', '--onlyprint', action='store_true', default=False, help='used this option if you only want to generate images without executing measures, dont forget to set the good path in using --topic with a "/" at the end')
parser.add_option('-C', '--onlyConstTime', action='store_true', default=False, help='only measures constant time problem')
parser.add_option('-V', '--onlyVarTime', action='store_true', default=False, help='only measures variable time problem')
parser.add_option('-m', '--measure', action='append', type='int', help='select all measure you want to produce, by default all are produced')
options, args = parser.parse_args()
logger(options.verbose, options.output)
return options
def logger(level_name, filename=LOG_DEFAULT_FILENAME):
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
filename=filename, filemode='a'
)
console = logging.StreamHandler()
console.setLevel(LEVELS.get(level_name, logging.NOTSET))
console.setFormatter(logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s'))
logging.getLogger('').addHandler(console)
options = parser()
if not options.onlyexecute:
import pylab
def get_boxplot_data( filename ):
try:
f = open( filename )
return [ [ float(value) for value in line.split() ] for line in f.readlines() ]
except:
raise ValueError('got an issue during the reading of file %s' % filename)
def do_measure( name, p, ps, P, d, ds, D, r=options.nRun, s=options.seed, v='logging' ):
OPENMP_EXEC_FORMAT='./test/t-openmp -p=%d --popStep=%d -P=%d -d=%d --dimStep=%d -D=%d -r=%d --seed=%d -v=%s -H=%s -C=%d -V=%d'
pwd = options.topic + name + '_'
cmd = OPENMP_EXEC_FORMAT % (p, ps, P, d, ds, D, r, s, v, pwd,
0 if options.onlyVarTime else 1,
0 if options.onlyConstTime else 1)
logging.info( cmd )
if not options.onlyprint:
os.system( cmd )
if not options.onlyexecute:
def generate( filenames ):
for cur in filenames:
filename = RESULT_FILE_FORMAT % (pwd, cur, p, ps, P, d, ds, D, r, s)
pylab.boxplot( get_boxplot_data( filename ) )
nonzero = lambda x: x if x > 0 else 1
iters = ( nonzero( P - p ) / ps ) * ( nonzero( D - d ) / ds )
pylab.xlabel('%d iterations from %d,%d to %d,%d' % ( iters, p, d, P, D) )
pylab.ylabel('%s - %s' % (cur, name))
pylab.savefig( filename + '.pdf', format='pdf' )
pylab.savefig( filename + '.png', format='png' )
pylab.cla()
pylab.clf()
if not options.onlyVarTime:
generate( ['speedup', 'efficiency', 'dynamicity'] )
if not options.onlyConstTime:
generate( ['variable_speedup', 'variable_efficiency', 'variable_dynamicity'] )
def main():
if not options.onlyprint:
logging.info('creates first the new topic repository %s', options.topic)
os.mkdir( options.topic )
logging.info('do all tests with r = %d and a common seed value = %d' % (options.nRun, options.seed))
logging.info('EA in time O(1) and O(n) - speedup measure Sp, Ep and Dp for P & D')
n = options.nProc
F = options.fixedBound
if options.measure is None or 1 in options.measure:
logging.info('(1) measure for all combinaisons of P n D')
do_measure( '1', 1*n, 10*n, 101*n, 1*n, 10*n, 101*n )
if options.measure is None or 2 in options.measure:
logging.info('(2) measure for P \in [%d, %d[ with D fixed to %d' % (1*n, 101*n, F))
do_measure( '2', 1*n, 1*n, 101*n, F, 1, F )
if options.measure is None or 3 in options.measure:
logging.info('(3) measure for P \in [%d, %d[ with ps = %d and D fixed to %d' % (1*n, 1001*n, 10*n, F))
do_measure( '3', 1*n, 10*n, 1001*n, F, 1, F )
if options.measure is None or 4 in options.measure:
logging.info('(4) measure for D \in [%d, %d[ with P fixed to %d' % (1*n, 101*n, F))
do_measure( '4', F, 1, F, 1*n, 1*n, 101*n )
if options.measure is None or 5 in options.measure:
logging.info('(5) measure for D \in [%d, %d[ with ds = %d and P fixed to %d' % (1*n, 1001*n, 10*n, F))
do_measure( '5', F, 1, F, 1*n, 10*n, 1001*n )
# when executed, just run main():
if __name__ == '__main__':
logging.debug('### plotting started ###')
main()
logging.debug('### plotting ended ###')

View file

@ -0,0 +1,88 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// t-selectOne.cpp
// This program test the breeder object
// (c) GeNeura Team, 1998
/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef __GNUG__
// to avoid long name warnings
#pragma warning(disable:4786)
#endif // __GNUG__
#include <ga/eoBin.h> // eoBin, eoPop, eoBreeder
#include <eoPop.h>
#include <ga/eoBitOp.h>
#include <eoUniformSelect.h>
#include <eoStochTournament.h>
#include <eoDetTournament.h>
//-----------------------------------------------------------------------------
typedef eoBin<float> Chrom;
#include "binary_value.h"
//-----------------------------------------------------------------------------
main()
{
const unsigned POP_SIZE = 8, CHROM_SIZE = 4;
unsigned i;
eoBinRandom<Chrom> random;
eoPop<Chrom> pop;
// Create the population
for (i = 0; i < POP_SIZE; ++i) {
Chrom chrom(CHROM_SIZE);
random(chrom);
BinaryValue()(chrom);
pop.push_back(chrom);
}
// print population
std::cout << "population:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << pop[i] << " " << pop[i].fitness() << std::endl;
// Declare 1-selectors
eoUniformSelect<Chrom> uSelect;
Chrom aChrom;
aChrom = uSelect( pop );
std::cout << "Uniform Select " << aChrom << " " << aChrom.fitness() << std::endl;
eoStochTournament<Chrom> sSelect(0.7);
aChrom = sSelect( pop );
std::cout << "Stochastic Tournament " << aChrom << " " << aChrom.fitness() << std::endl;
eoDetTournament<Chrom> dSelect(3);
aChrom = dSelect( pop );
std::cout << "Deterministic Tournament " << aChrom << " " << aChrom.fitness() << std::endl;
return 0;
}
//-----------------------------------------------------------------------------