Paradiseo-eo sources added

git-svn-id: svn://scm.gforge.inria.fr/svnroot/paradiseo@40 331e1502-861f-0410-8da2-ba01fb791d7f
This commit is contained in:
legrand 2006-12-12 14:49:08 +00:00
commit c3aec878e5
3609 changed files with 342772 additions and 0 deletions

View file

@ -0,0 +1,29 @@
*.o
*.csv
*.sav
.deps
Makefile
Makefile.in
t-eo
t-eobin
t-eobreeder
t-eofitness
t-eoinclusion
t-eoinsertion
t-eolottery
t-eoproblem
t-eogeneration
t-eoNonUniform
t-eo2dVector
t-eoEasyEA
t-eoUniform
t-eoRandom
t-eoCheckpointing
t-eoVector
t-eoAtomOps
t-selectOne
t-eoStateAndParser
t-eoGOpSel
t-eoExternalEO
t-eoESFull
t-eoSymreg

View file

@ -0,0 +1,53 @@
/.cvsignore/1.13/Mon Nov 6 12:37:58 2000//
/Makefile.am/1.70/Wed Dec 7 15:51:32 2005//
/RoyalRoad.h/1.3/Thu Jun 21 12:03:17 2001//
/binary_value.h/1.5/Sat Nov 17 07:54:12 2001//
/fitness_traits.cpp/1.4/Thu Feb 27 19:20:30 2003//
/real_value.h/1.8/Mon May 21 04:10:55 2001//
/run_tests/1.5/Wed Nov 7 15:23:24 2001//
/t-MGE-control.cpp/1.7/Thu Oct 6 17:22:40 2005//
/t-MGE.cpp/1.8/Thu Oct 6 17:22:40 2005//
/t-MGE1bit.cpp/1.8/Thu Oct 6 17:22:40 2005//
/t-eo.cpp/1.4/Thu Feb 27 19:20:29 2003//
/t-eo2dVector.cc/1.1/Fri Oct 1 16:36:04 1999//
/t-eoAtomOps.cpp/1.4/Thu Feb 27 19:20:29 2003//
/t-eoBaseFunctions.cpp/1.3/Thu Feb 27 19:20:29 2003//
/t-eoCMAES.cpp/1.2/Sun Mar 26 13:33:25 2006//
/t-eoCheckpointing.cpp/1.8/Mon Sep 26 10:18:15 2005//
/t-eoESAll.cpp/1.7/Mon Oct 10 21:42:31 2005//
/t-eoESFull.cpp/1.14/Mon Sep 26 10:18:15 2005//
/t-eoESOps.cpp/1.3/Thu Feb 27 19:20:28 2003//
/t-eoEasyEA.cpp/1.6/Thu Feb 27 19:20:28 2003//
/t-eoExternalEO.cpp/1.6/Thu Feb 27 19:20:28 2003//
/t-eoFitnessAssembled.cpp/1.1/Wed Apr 2 21:10:26 2003//
/t-eoFitnessAssembledEA.cpp/1.2/Mon Sep 20 14:11:23 2004//
/t-eoFunctor.cpp/1.2/Wed Aug 23 12:03:01 2000//
/t-eoGA.cpp/1.8/Thu Feb 27 19:20:28 2003//
/t-eoGOpSel.cpp/1.8/Thu Feb 27 19:20:27 2003//
/t-eoGenOp.cpp/1.12/Wed Sep 28 21:49:26 2005//
/t-eoNonUniform.cpp/1.3/Thu Feb 27 19:20:26 2003//
/t-eoPBIL.cpp/1.7/Wed Oct 5 21:34:19 2005//
/t-eoPareto.cpp/1.15/Wed Oct 5 21:34:19 2005//
/t-eoParetoFitness.cpp/1.8/Wed Sep 29 18:37:20 2004//
/t-eoRandom.cpp/1.13/Thu Feb 27 19:20:24 2003//
/t-eoReal.cpp/1.6/Thu Feb 27 19:20:24 2003//
/t-eoReplacement.cpp/1.6/Thu Feb 27 19:20:23 2003//
/t-eoRoulette.cpp/1.1/Wed Jun 4 09:34:26 2003//
/t-eoSSGA.cpp/1.4/Thu Feb 27 19:20:22 2003//
/t-eoSelect.cpp/1.12/Mon Sep 26 10:18:15 2005//
/t-eoSharing.cpp/1.4/Wed Sep 28 21:49:26 2005//
/t-eoStateAndParser.cpp/1.9/Mon Sep 26 10:18:15 2005//
/t-eoSymreg.cpp/1.15/Thu Feb 27 19:20:22 2003//
/t-eoUniform.cpp/1.3/Thu Feb 27 19:20:22 2003//
/t-eoVector.cpp/1.7/Wed Sep 28 21:49:26 2005//
/t-eoVirus.cpp/1.5/Tue Sep 21 10:23:32 2004//
/t-eobin.cpp/1.21/Wed Sep 28 21:49:26 2005//
/t-eobreeder.cpp/1.13/Thu Feb 27 19:20:29 2003//
/t-eofitness.cpp/1.7/Thu Feb 27 19:20:28 2003//
/t-eogeneration.cpp/1.7/Thu Feb 27 19:20:27 2003//
/t-eoinclusion.cpp/1.8/Thu Feb 27 19:20:27 2003//
/t-eoinsertion.cpp/1.6/Thu Feb 27 19:20:26 2003//
/t-eolottery.cpp/1.5/Thu Feb 27 19:20:26 2003//
/t-eoproblem.cpp/1.4/Thu Feb 27 19:20:25 2003//
/t-selectOne.cpp/1.6/Thu Feb 27 19:20:20 2003//
D

View file

@ -0,0 +1 @@
eo/test

View file

@ -0,0 +1 @@
:ext:evomarc@eodev.cvs.sourceforge.net:/cvsroot/eodev

View file

@ -0,0 +1,93 @@
###############################################################################
##
## Makefile.am for eo/test
##
###############################################################################
LIBEO = $(top_builddir)/src/libeo.a
LIBEOUTILS = $(top_builddir)/src/utils/libeoutils.a
LIBES = $(top_builddir)/src/es/libes.a
LIBGA = $(top_builddir)/src/ga/libga.a
LIBCMA = $(top_builddir)/src/es/libcma.a
# PLEASE don't break the line (see create_batch.sh)
check_PROGRAMS = t-eoParetoFitness \
t-eoPareto \
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
TESTS = $(check_PROGRAMS) \
run_tests # This script can be used to check command-line arguments
noinst_HEADERS = binary_value.h real_value.h RoyalRoad.h
DEPS = $(LIBGA) $(LIBES) $(LIBCMA) $(LIBEOUTILS) $(LIBEO)
INCLUDES = -I$(top_srcdir)/src -I$(srcdir)/../src
LIBS = $(DEPS)
CLEANFILES = monitor.csv t-eoRandom.out
EXTRA_DIST = run_tests
# extra flags for specific targets
t_eoVirus_CXXFLAGS = $(AM_CXXFLAGS) -I$(top_srcdir)/contrib
t_MGE_CXXFLAGS = -I$(top_srcdir)/contrib/MGE
t_MGE1bit_CXXFLAGS = -I$(top_srcdir)/contrib/MGE
t_MGE_control_CXXFLAGS = -I$(top_srcdir)/contrib/MGE
# Specify source-files,
# otherwise automake/make looks for C sources
#
t_eoRandom_SOURCES = t-eoRandom.cpp
t_eofitness_SOURCES = t-eofitness.cpp
t_eoFitnessAssembledEA_SOURCES = t-eoFitnessAssembledEA.cpp
t_eobin_SOURCES = t-eobin.cpp
t_eoVirus_SOURCES = t-eoVirus.cpp
t_MGE1bit_SOURCES = t-MGE1bit.cpp
t_MGE_SOURCES = t-MGE.cpp
t_MGE_control_SOURCES = t-MGE-control.cpp
t_eoStateAndParser_SOURCES = t-eoStateAndParser.cpp
t_eoCheckpointing_SOURCES = t-eoCheckpointing.cpp
t_eoReplacement_SOURCES = t-eoReplacement.cpp
t_eoSelect_SOURCES = t-eoSelect.cpp
t_eoExternalEO_SOURCES = t-eoExternalEO.cpp
t_eoSymreg_SOURCES = t-eoSymreg.cpp
t_eo_SOURCES = t-eo.cpp
t_eoGenOp_SOURCES = t-eoGenOp.cpp
t_eoVector_SOURCES = t-eoVector.cpp
t_eoGA_SOURCES = t-eoGA.cpp
t_eoReal_SOURCES = t-eoReal.cpp
t_eoESAll_SOURCES = t-eoESAll.cpp
t_eoSSGA_SOURCES = t-eoSSGA.cpp
t_eoPareto_SOURCES = t-eoPareto.cpp
t_eoParetoFitness_SOURCES = t-eoParetoFitness.cpp
t_eoPBIL_SOURCES = t-eoPBIL.cpp
t_eoFitnessAssembled_SOURCES = t-eoFitnessAssembled.cpp
t_eoRoulette_SOURCES = t-eoRoulette.cpp
t_eoSharing_SOURCES = t-eoSharing.cpp
t_eoCMAES_SOURCES = t-eoCMAES.cpp

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: /cvsroot/eodev/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;
}

View file

@ -0,0 +1,433 @@
#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,19 @@
#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();
}

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<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 );
eoInitVirus1bit<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
VirusShiftMutation<float> vm;
VirusTransmission<float> vt;
VirusBitFlip<float> 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,23 @@
//-----------------------------------------------------------------------------
// t-eo.cpp
//-----------------------------------------------------------------------------
#include <eo> // EO
//-----------------------------------------------------------------------------
typedef EO<float> Chrom;
//-----------------------------------------------------------------------------
int main()
{
Chrom chrom1, chrom2;
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,66 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
t-eoAtomOps.cpp
Program that tests the atomic operator classes
(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 _MSC_VER
#pragma warning(disable:4786)
#endif
#include <string>
#include <iostream>
#include <iterator>
using namespace std;
// Operators we are going to test
#include <eoAtomCreep.h>
#include <eoAtomBitFlip.h>
#include <eoAtomRandom.h>
#include <eoAtomMutation.h>
// Several EOs
#include <other/eoString.h>
// RNGs
#include <eoNegExp.h>
main(int argc, char *argv[]) {
eoString<float> aString("123456");
eoAtomCreep<char> creeper;
eoAtomMutation< eoString<float> > mutator( creeper, 0.5 );
eoNegExp<char> charNE( 2 );
eoAtomRandom<char> randomer( charNE );
eoAtomMutation< eoString<float> > mutator2 ( randomer, 0.5 );
std::cout << "Before aString " << aString << std::endl;
mutator( aString);
std::cout << " after mutator " << aString << std::endl;
mutator2( aString);
std::cout << " after mutator2 " << aString << std::endl;;
return 0; // to avoid VC++ complaints
}

View file

@ -0,0 +1,26 @@
#include <eoBaseFunctions.h>
#include <iostream>
using namespace std;
struct eo1 : public eoF<void>
{
void operator()(void) {}
};
struct eo2 : public eoF<int>
{
int operator()(void) { return 1; }
};
int main()
{
eo1 _1; _1();
eo2 _2;
int i = _2();
std::cout << i << '\n';
return i;
}

View file

@ -0,0 +1,128 @@
#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 (int 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] = "-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,183 @@
//-----------------------------------------------------------------------------
// 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 <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,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,116 @@
// Program to test several EO-ES features
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <string>
#include <iostream>
#include <iterator>
using namespace std;
// general
#include <utils/eoParser.h> // though contained in all others!
// evolution specific
#include <eoEvalFuncPtr.h>
//#include <eoSequentialOpHolder.h>
//#include <eoFullEA.h>
// representation specific
#include <es/eoESFullChrom.h> // though contained in following
//#include <eoESReco.h>
#include <es/eoESFullMut.h>
//#include <eoESRandomize.h>
// this fitness
#include "real_value.h" // the sphere fitness
// Now the main
///////////////
typedef eoESFullChrom<float> Ind;
main(int argc, char *argv[]) {
unsigned mu, lambda;
bool comma;
// Create the command-line parser
Parser parser( argc, argv, "Basic EA for vector<float> with adaptive mutations");
//reproducible random seed - thanks, Maarten
InitRandom(parser);
// a first Ind, reading its parameters from the parser
// will be used later to inialize the whole population
Ind FirstEO(parser);
// Evaluation
// here we should call some parser-based constructor,
// as many evaluation function need parameters
// and also have some preliminary stuffs to do
eoEvalFuncPtr<Ind> eval( real_value );
// recombination and mutation operators, reading their parameters from the parser
eoESMutate<float> MyMut(parser,
FirstEO.StdDevLength(), FirstEO.size(),
FirstEO.CorCffLength() );
std::cout << "First EO " << FirstEO << std::endl;
MyMut(FirstEO);
std::cout << "First EO mutated" << FirstEO << std::endl;
/*
// Evolution and population parameters
eoScheme<Ind> the_scheme(parser);
// recombination and mutation operators, reading their parameters from the parser
eoESReco<float> MyReco(parser, FirstEO);
eoESMutate<float> MyMut(parser, FirstEO);
// termination conditions read by the parser
eoTermVector<Ind> the_terms(parser);
// Initialization of the population
// shoudl be called using the parser, in case you want to read from file(s)
eoESRandomize<float> randomize; // an eoESInd randomnizer
eoPop<Ind> pop(the_scheme.PopSize(), FirstEO, randomize);
// eval(pop); // shoudl we call it from inside the constructor???
// ALL parmeters have been read: write them out
// Writing the parameters on arv[0].status
// but of course this can be modified - see the example parser.cpp
parser.outputParam();
// except the help parameter???
if( parser.getBool("-h" , "--help" , "Shows this help")) {
parser.printHelp();
exit(1);
}
unsigned i, iind;
std::cout << "Initial population: \n" << std::endl;
for (i = 0; i < pop.size(); ++i) {
eval(pop[i]);
std::cout << pop[i].fitness() << "\t" << pop[i] << std::endl;
}
// the Operators
eoSequentialOpHolder <Ind> seqholder;
// seqholder.addOp(MyReco, 1.0);
seqholder.addOp(MyMut, 1.0);
// One generation
eoEvolStep<Ind> evol_scheme(the_scheme, seqholder, eval);
// the algorithm:
eoFullEA<Ind> ea(evol_scheme, the_terms);
ea(pop);
std::cout << "Final population: \n" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << pop[i].fitness() << "\t" << pop[i] << std::endl;
return 0;
*/
}

View file

@ -0,0 +1,84 @@
//-----------------------------------------------------------------------------
// t-eoEasyEA.cpp
//-----------------------------------------------------------------------------
#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,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,105 @@
// -*- 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,49 @@
#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,131 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
t-eoGOpSel.cpp
Testing proportional operator selectors
(c) Maarten Keijzer and GeNeura Team, 2000
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 <iostream>
#include <ga/eoBin.h> // eoBin, eoPop, eoBreeder
#include <eoPop.h>
#include <ga/eoBitOp.h>
#include <eoProportionalGOpSel.h>
#include <eoSequentialGOpSelector.h>
#include <eoRandomIndiSelector.h>
#include <eoDetTournamentIndiSelector.h>
#include <eoDetTournamentInserter.h>
#include <eoStochTournamentInserter.h>
#include <eoGOpBreeder.h>
#include <utils/eoRNG.h>
#include <utils/eoState.h>
// Fitness evaluation
#include "binary_value.h"
//-----------------------------------------------------------------------------
typedef eoBin<float> Chrom;
//-----------------------------------------------------------------------------
main()
{
rng.reseed(42); // reproducible random seed
const unsigned POP_SIZE = 8, CHROM_SIZE = 4;
unsigned i;
eoBinRandom<Chrom> random;
eoPop<Chrom> pop;
for (i = 0; i < POP_SIZE; ++i)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
chrom.fitness(binary_value(chrom));
pop.push_back(chrom);
}
std::cout << "population:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << pop[i] << " " << pop[i].fitness() << std::endl;
eoBinBitFlip<Chrom> bitflip;
eoBinCrossover<Chrom> xover;
eoEvalFuncPtr<Chrom> eval(binary_value);
//Create the proportional operator selector and add the
// two operators creatd above to it.
eoProportionalGOpSel<Chrom > propSel;
eoSequentialGOpSel<Chrom> seqSel;
propSel.addOp(bitflip, 0.5);
propSel.addOp(xover, 0.5);
// seqSel selects operator in sequence, creating a combined operator
// add a bitflip, an xover and another bitflip
seqSel.addOp(bitflip, 0.25);
seqSel.addOp(xover, 0.5);
seqSel.addOp(bitflip, 0.25);
eoRandomIndiSelector<Chrom> selector1;
eoDetTournamentIndiSelector<Chrom> selector2(2);
eoBackInserter<Chrom> inserter1;
eoDetTournamentInserter<Chrom> inserter2(eval, 2);
eoStochTournamentInserter<Chrom> inserter3(eval, 0.9f);
eoGOpBreeder<Chrom> breeder1(propSel, selector1);
eoGOpBreeder<Chrom> breeder2(seqSel, selector1);
eoGOpBreeder<Chrom> breeder3(propSel, selector2);
eoGOpBreeder<Chrom> breeder4(seqSel, selector2);
// test the breeders
breeder1(pop);
breeder2(pop);
breeder3(pop);
breeder4(pop);
eoState state;
state.registerObject(pop);
state.save(std::std::cout);
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,428 @@
// -*- 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>
{
typedef double Type;
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 << std::ends;
_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("mon1");
monop clone("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\n" << 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,31 @@
//-----------------------------------------------------------------------------
// t-eoNonUniform.cc
//-----------------------------------------------------------------------------
#include <iostream>
#include <eo>
//-----------------------------------------------------------------------------
main()
{
eoNonUniform nu(1000);
std::cout << "----------------------------------------------------------" << std::endl
<< "nu.step() = " << nu.step()
<< "\t nu.num_step() = " << nu.num_step() << std::endl
<< "----------------------------------------------------------" << std::endl;
eoLinear l1(0, 1, nu), l2(1, 0, nu);
eoNegExp2 n1(0.1, 8, nu), n2(0.75, 3, nu);
for (; nu; ++nu)
{
std::cout << nu.step()
<< "\t" << l1() << "\t" << l2()
<< "\t" << n1() << "\t" << n2()
<< std::endl;
}
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,141 @@
// -*- 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 */
#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())
{
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);
}
// 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,248 @@
#include <eo>
//#include <utils/eoMOFitnessStat.h>
#include <eoNDSorting.h>
#include <eoParetoFitness.h>
using namespace std;
// Look: overloading the maximization without overhead (thing can be inlined)
class MinimizingFitnessTraits : public eoParetoFitnessTraits
{
public :
static bool maximizing(int) { return false; }
};
typedef eoParetoFitness<MinimizingFitnessTraits> fitness_type;
const unsigned chromsize=3;
const double minval = -5;
const double maxval = 5;
struct eoDouble : public EO<fitness_type>
{
double value[chromsize];
};
class Mutate : public eoMonOp<eoDouble>
{
bool operator()(eoDouble& _eo)
{
for (unsigned i = 0; i < chromsize; ++i)
{
if (rng.flip(1./chromsize))
_eo.value[i] += rng.normal() * 0.1 * _eo.value[i];
if (_eo.value[i] < minval)
_eo.value[i] = minval;
else if (_eo.value[i] > maxval)
_eo.value[i] = maxval;
}
return true;
}
};
class Eval : public eoEvalFunc<eoDouble>
{
void operator()(eoDouble& _eo)
{
vector<double> x(_eo.value, _eo.value + chromsize);
fitness_type f;
for (unsigned i = 0; i < chromsize; ++i)
{
if (i < chromsize-1)
{
f[0] += -10.0 * exp(-0.2 * sqrt(x[i]*x[i] + x[i+1]*x[i+1]));
}
f[1] += pow(fabs(x[i]), 0.8) + 5 * pow(sin(x[i]),3.);
}
_eo.fitness(f);
}
};
class Init : public eoInit<eoDouble>
{
void operator()(eoDouble& _eo)
{
_eo.value[0] = rng.uniform();
double range = maxval - minval;
for (unsigned i = 1; i < chromsize; ++i)
_eo.value[i] = rng.uniform() * range + minval;
_eo.invalidate();
}
};
/** @brief An elitist non-dominated sorted replacement scheme.
Trying out an elitist non-dominated sorted replacement scheme.
*/
template <class EOT, class WorthT = double>
class eoNDPlusReplacement : public eoReplacement<EOT>
{
public:
// using eoNDPlusReplacement< EOT, WorthT >::first;
eoNDPlusReplacement(eoPerf2Worth<EOT, WorthT>& _perf2worth)
: perf2worth(_perf2worth)
{}
struct WorthPair : public pair<WorthT, const EOT*>
{
bool operator<(const WorthPair& other) const
{ return other.first < this->first; }
};
void operator()(eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
{
unsigned sz = _parents.size();
_parents.reserve(_parents.size() + _offspring.size());
std::copy(_offspring.begin(), _offspring.end(), back_inserter(_parents));
// calculate worths
perf2worth(_parents);
perf2worth.sort_pop(_parents);
perf2worth.resize(_parents, sz);
_offspring.clear();
}
private :
eoPerf2Worth<EOT, WorthT>& perf2worth;
};
template <class EOT>
eoPerf2Worth<EOT, double>& make_perf2worth(eoParser& parser, eoState& state)
{
unsigned what = parser.createParam(unsigned(1), "perf2worth", "worth mapping indicator : \n\t \
0: non_dominated sorting \n\t\
1: non_dominated sorting 2 \n\t\
2: simple ranking \n\t", 'w').value();
switch (what)
{
case 1 : return state.storeFunctor(new eoNDSorting_II<EOT>());
case 2 :
{
eoDominanceMap<eoDouble>& dominance = state.storeFunctor(new eoDominanceMap<EOT>);
return state.storeFunctor(new eoParetoRanking<EOT>(dominance));
}
}
//default
if (what > 2)
{
std::cout << "Warning, need an integer < 3 for perf2worth" << std::endl;
// should actually set parser flag, but I don't care
}
return state.storeFunctor(new eoNDSorting_I<EOT>(0.5));
}
template <class EOT>
eoSelectOne<EOT>& make_selector(eoParser& parser, eoState& state, eoPerf2Worth<EOT, double>& perf2worth)
{
unsigned tournamentsize = parser.createParam(unsigned(2), "tournament_size", "Tournament Size", 't').value();
double stochtour = parser.createParam(unsigned(0.95), "tournament_prob", "Probability in stochastic tournament").value();
switch (parser.createParam(unsigned(0), "selector", "Which selector (too lazy to explain: use the source)", 's').value())
{
case 1 : return state.storeFunctor(new eoStochTournamentWorthSelect<eoDouble>(perf2worth, stochtour));
case 2 : return state.storeFunctor(new eoRouletteWorthSelect<eoDouble>(perf2worth));
case 3 : return state.storeFunctor(new eoRandomSelect<EOT>);
}
// default
return state.storeFunctor(new eoDetTournamentWorthSelect<eoDouble>(perf2worth, tournamentsize));
}
// Test pareto dominance and perf2worth, and while you're at it, test the eoGnuPlot monitor as well
void the_main(int argc, char* argv[])
{
Init init;
Eval eval;
Mutate mutate;
eoParser parser(argc, argv);
eoState state;
unsigned num_gen = parser.createParam(unsigned(50), "num_gen", "number of generations to run", 'g').value();
unsigned pop_size = parser.createParam(unsigned(100), "pop_size", "population size", 'p').value();
eoPop<eoDouble> pop(pop_size, init);
// Look, a factory function
eoPerf2Worth<eoDouble, double>& perf2worth = make_perf2worth<eoDouble>(parser, state);
// Look: another factory function, now for selection
eoSelectOne<eoDouble>& select = make_selector<eoDouble>(parser, state, perf2worth);
// One general operator
eoProportionalOp<eoDouble> opsel;
opsel.add(mutate, 1.0);
// the breeder
eoGeneralBreeder<eoDouble> breeder(select, opsel);
// replacement
eoNDPlusReplacement<eoDouble> replace(perf2worth);
unsigned long generation = 0;
eoGenContinue<eoDouble> gen(num_gen, generation);
eoCheckPoint<eoDouble> cp(gen);
eoMOFitnessStat<eoDouble> fitness0(0, "FirstObjective");
eoMOFitnessStat<eoDouble> fitness1(1, "SecondObjective");
cp.add(fitness0);
cp.add(fitness1);
eoGnuplot1DSnapshot snapshot("pareto");
//snapshot.with(eoGnuplot::Points(3));
cp.add(snapshot);
snapshot.add(fitness0);
snapshot.add(fitness1);
// the algo
eoEasyEA<eoDouble> ea(cp, eval, breeder, replace);
if (parser.userNeedsHelp())
{
parser.printHelp(std::cout);
return;
}
apply<eoDouble>(eval, pop);
ea(pop);
}
int main(int argc, char* argv[])
{
try
{
the_main(argc, argv);
}
catch (std::exception& e)
{
std::cout << "Exception thrown: " << e.what() << std::endl;
throw e; // make sure it does not pass the test
}
}
// Local Variables:
// mode: C++
// c-file-style: "Stroustrup"
// End:

View file

@ -0,0 +1,196 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// t-eoParetoFitness.cpp
// (c) Maarten Keijzer
/*
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: mak@dhi.dk
30/01/02 - MS - Added the eoVariableParetoTraits - and the compare Fn
*/
//-----------------------------------------------------------------------------
#include <cassert>
#include <iostream>
#include "eoParetoFitness.h"
using namespace std;
/** test program for Pareto Fitness */
class MinimizingTraits : public eoParetoFitnessTraits
{
public :
static bool maximizing(int) { return false; }
};
template <class F>
void compare(F & _eo1, F & _eo2)
{
if (_eo1.dominates(_eo2))
std::cout << _eo1 << " dominates " << _eo2 << std::endl;
else if (_eo2.dominates(_eo1))
std::cout << _eo2 << " dominates " << _eo1 << std::endl;
else
std::cout << "None of " << _eo1 << " and " << _eo2 << "dominates the other" << std::endl;
return;
}
int main()
{
typedef eoParetoFitness<> MaxFitness;
typedef eoParetoFitness<MinimizingTraits> MinFitness;
typedef eoParetoFitness<eoVariableParetoTraits> VarFitness;
try{
MaxFitness f0;
f0[0] = 0.0;
f0[1] = 1.0;
MaxFitness f1;
f1[0] = 1.0;
f1[1] = 0.0;
MaxFitness f2;
f2[0] = 0.0;
f2[1] = 0.5;
// now f0 should dominate f2;
if (!f0.dominates(f2))
{
std::cout << f2 << " not dominated by " << f0;
throw;
}
// f0 and f1 should not dominate each other
if (f0.dominates(f1) || f1.dominates(f0))
{
std::cout << f0 << " and " << f1 << " dominate";
throw;
}
if (! (f0 == f0))
{
std::cout << "f0 == f0 failed" << std::endl;
throw;
}
// test ctors and such
MaxFitness f3 = f0;
f3[0] += 1e-9;
// test tolerance
assert(f3 == f0);
MinFitness m0;
MinFitness m1;
MinFitness m2;
MinFitness m3;
m0[0] = 0.0;
m0[1] = 1.0;
m1[0] = 1.0;
m1[1] = 0.0;
m2[0] = 0.0;
m2[1] = 0.5;
m3[0] = 0.5;
m3[1] = 0.5;
//m2 should dominate m0
assert(m2.dominates(m0));
assert(!m1.dominates(m0));
assert(!m0.dominates(m1));
assert(!m0.dominates(m2)); // (m2 < m0));
assert(m2.dominates(m3)); //m3 < m2);
assert(!m3.dominates(m2)); // (m2 < m3));
assert(m2.dominates(m3)); //m2 > m3);
//////////////////////////////////////////
// now the run-time set-able number of objectives
////////////////////////////////////////////
std::cout << "On y va" << std::endl;
// setup fitness WARNING do not try to allocate any EO before that (runtime error)
vector<bool> b(2, true);
b[0]=true;
b[1]=false;
VarFitness::setUp(2, b);
std::cout << "\nMAXimizing on Obj 0 and MINimizing on Obj 1\n";
VarFitness mv0;
VarFitness mv1;
VarFitness mv2;
VarFitness mv3;
mv0[0] = 0.0;
mv0[1] = 1.0;
mv1[0] = 1.0;
mv1[1] = 0.0;
mv2[0] = 0.0;
mv2[1] = 0.5;
mv3[0] = 0.5;
mv3[1] = 0.5;
compare <VarFitness>(mv0,mv1);
compare <VarFitness>(mv0,mv2);
compare <VarFitness>(mv0,mv3);
compare <VarFitness>(mv1,mv2);
compare <VarFitness>(mv1,mv3);
compare <VarFitness>(mv2,mv3);
std::cout << "\nChanging now the min <-> max\n";
b[0]=false;
b[1]=true;
VarFitness::setUp(2, b);
std::cout << "\nMINimizing on Obj 0 and MAXimizing on Obj 1\n";
compare <VarFitness>(mv0,mv1);
compare <VarFitness>(mv0,mv2);
compare <VarFitness>(mv0,mv3);
compare <VarFitness>(mv1,mv2);
compare <VarFitness>(mv1,mv3);
compare <VarFitness>(mv2,mv3);
std::cout << "\nTesting WARNING\n";
b.resize(3);
b[0]=false;
b[1]=true;
b[2]=true;
VarFitness::setUp(3, b);
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}

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,68 @@
#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,224 @@
//-----------------------------------------------------------------------------
// to avoid long name warnings
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <stdexcept> // runtime_error
// general
#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,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,295 @@
#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(void) { init(); }
SymregNode(Operator _op) { op = _op; }
virtual ~SymregNode(void) {}
// arity function, need this function!
int arity(void) const { return op == X? 0 : 2; }
void randomize(void) {}
// 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, r2;
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)
result = 1.0; // protection a la Koza, realistic implementations should maybe throw an exception
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(void) const { return op; }
protected :
void init(void) { 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(void) : 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);
}

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,77 @@
/* -*- 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,87 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// t-eobreeder.cpp
// This program test the breeder object
// (c) GeNeura Team, 1998
/*
This library 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 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
*/
//-----------------------------------------------------------------------------
#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 <eoProportionalOpSel.h>
#include <eoBreeder.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;
BinaryValue eval;
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 << pop[i] << " " << pop[i].fitness() << std::endl;
eoBinBitFlip<Chrom> bitflip;
eoBinCrossover<Chrom> xover;
eoProportionalOpSel<Chrom> propSel;
eoBreeder<Chrom> breeder( propSel );
propSel.addOp(bitflip, 0.25);
propSel.addOp(xover, 0.75);
breeder(pop);
// reevaluation of fitness
for_each(pop.begin(), pop.end(), BinaryValue());
std::cout << "new population:" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << pop[i] << " " << pop[i].fitness() << std::endl;
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,90 @@
//-----------------------------------------------------------------------------
// 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,145 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
t-eogeneration.cpp
Testing the eoGeneration classes, and classes related to it
(c) GeNeura Team, 1999, 2000
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
*/
//-----------------------------------------------------------------------------//
// to avoid long name warnings
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#include <eoGeneration.h>
#include <eoEvalFuncPtrCnt.h>
#include "binary_value.h"
//-----------------------------------------------------------------------------
typedef eoBin<float> Chrom;
//-----------------------------------------------------------------------------
main()
{
const unsigned POP_SIZE = 8, CHROM_SIZE = 16;
unsigned i;
eoBinRandom<Chrom> random;
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;
// GA generation
eoGeneration<Chrom> generation(lottery, breeder, inclusion, eval);
// evolution
unsigned g = 0;
do {
try
{
generation(pop);
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
std::cout << "pop[" << ++g << "]" << std::endl;
for (i = 0; i < pop.size(); ++i)
std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl;
} while (pop[0].fitness() < pow(2.0, CHROM_SIZE) - 1);
// Try again, with a "counted" evaluation function
// GA generation
// Evaluation
eoEvalFuncPtrCnt<Chrom> eval2( binary_value );
eoPop<Chrom> pop2;
for (i = 0; i < POP_SIZE; ++i)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
binary_value(chrom);
eval2(chrom);
pop2.push_back(chrom);
}
eoGeneration<Chrom> generation2(lottery, breeder, inclusion, eval2);
// evolution
do {
try
{
generation2(pop2);
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what() << std::endl;;
exit(EXIT_FAILURE);
}
std::cout << "pop[" << ++g << "]" << std::endl;
for (i = 0; i < pop2.size(); ++i)
std::cout << "\t" << pop2[i] << " " << pop[i].fitness() << std::endl;
} while (pop2[0].fitness() < pow(2.0, CHROM_SIZE) - 1);
std::cout << "Number of evaluations " << eval2.getNumOfEvaluations() << std::endl;
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,97 @@
//-----------------------------------------------------------------------------
// t-eoinclusion.cpp
//-----------------------------------------------------------------------------
#include <ga/eoBin.h>
#include <eoPop.h>
#include <eoInclusion.h>
//-----------------------------------------------------------------------------
typedef eoBin<float> Chrom;
#include "binary_value.h"
//-----------------------------------------------------------------------------
main()
{
const unsigned CHROM_SIZE = 4;
eoBinRandom<Chrom> random;
BinaryValue eval;
for (unsigned POP_SIZE = 4; POP_SIZE <=6; POP_SIZE++)
{
eoPop<Chrom> pop;
unsigned i;
for ( i = 0; i < POP_SIZE; i++)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
eval(chrom);
pop.push_back(chrom);
}
for (unsigned POP2_SIZE = 4; POP2_SIZE <=6; POP2_SIZE++)
{
eoPop<Chrom> pop2, pop3, pop4, pop5;
for (i = 0; i < POP2_SIZE; i++)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
eval(chrom);
pop2.push_back(chrom);
}
std::cout << "--------------------------------------------------" << std::endl
<< "breeders \tpop" << std::endl
<< "--------------------------------------------------" << std::endl;
for (i = 0; i < max(pop.size(), pop2.size()); i++)
{
if (pop.size() > i)
std::cout << pop[i] << " " << pop[i].fitness() << " \t";
else
std::cout << "\t\t";
if (pop2.size() > i)
std::cout << pop2[i] << " " << pop2[i].fitness();
std::cout << std::endl;
}
eoInclusion<Chrom> inclusion(0.75);
pop3 = pop2;
inclusion(pop, pop3);
eoInclusion<Chrom> inclusion2;
pop4 = pop2;
inclusion2(pop, pop4);
eoInclusion<Chrom> inclusion3(1.5);
pop5 = pop2;
inclusion3(pop, pop5);
std::cout << std::endl
<< "0.75 \t\t1.0 \t\t1.5" << std::endl
<< "---- \t\t--- \t\t---" << std::endl;
for (i = 0; i < pop5.size(); i++)
{
if (pop3.size() > i)
std::cout << pop3[i] << " " << pop3[i].fitness() << " \t";
else
std::cout << " \t\t";
if (pop4.size() > i)
std::cout << pop4[i] << " " << pop4[i].fitness() << " \t";
else
std::cout << " \t\t";
if (pop5.size() > i)
std::cout << pop5[i] << " " << pop5[i].fitness();
std::cout << std::endl;
}
}
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,108 @@
//-----------------------------------------------------------------------------
// t-eoinsertion.cpp
//-----------------------------------------------------------------------------
#include <eo> // eoBin, eoPop, eoInsertion
//-----------------------------------------------------------------------------
typedef eoBin<float> Chrom;
//-----------------------------------------------------------------------------
void binary_value(Chrom& chrom)
{
float sum = 0;
for (unsigned i = 0; i < chrom.size(); i++)
if (chrom[i])
sum += pow(2, chrom.size() - i - 1);
chrom.fitness(sum);
}
//-----------------------------------------------------------------------------
main()
{
const unsigned CHROM_SIZE = 4;
unsigned i;
eoBinRandom<Chrom> random;
for (unsigned POP_SIZE = 4; POP_SIZE <=6; POP_SIZE++)
{
eoPop<Chrom> pop;
for (i = 0; i < POP_SIZE; i++)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
binary_value(chrom);
pop.push_back(chrom);
}
for (unsigned POP2_SIZE = 4; POP2_SIZE <=6; POP2_SIZE++)
{
eoPop<Chrom> pop2, pop3, pop4, pop5, popx;
for (i = 0; i < POP2_SIZE; i++)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
binary_value(chrom);
pop2.push_back(chrom);
}
std::cout << "--------------------------------------------------" << std::endl
<< "breeders \tpop" << std::endl
<< "--------------------------------------------------" << std::endl;
for (i = 0; i < max(pop.size(), pop2.size()); i++)
{
if (pop.size() > i)
std::cout << pop[i] << " " << pop[i].fitness() << " \t";
else
std::cout << "\t\t";
if (pop2.size() > i)
std::cout << pop2[i] << " " << pop2[i].fitness();
std::cout << std::endl;
}
eoInsertion<Chrom> insertion(0.75);
popx = pop;
pop3 = pop2;
insertion(popx, pop3);
eoInsertion<Chrom> insertion2;
popx = pop;
pop4 = pop2;
insertion2(popx, pop4);
eoInsertion<Chrom> insertion3(1.5);
popx = pop;
pop5 = pop2;
insertion3(popx, pop5);
std::cout << std::endl
<< "0.75 \t\t1.0 \t\t1.5" << std::endl
<< "---- \t\t--- \t\t---" << std::endl;
for (i = 0; i < pop5.size(); i++)
{
if (pop3.size() > i)
std::cout << pop3[i] << " " << pop3[i].fitness() << " \t";
else
std::cout << " \t\t";
if (pop4.size() > i)
std::cout << pop4[i] << " " << pop4[i].fitness() << " \t";
else
std::cout << " \t\t";
if (pop5.size() > i)
std::cout << pop5[i] << " " << pop5[i].fitness();
std::cout << std::endl;
}
}
}
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,54 @@
//-----------------------------------------------------------------------------
// t-eolottery.cpp
//-----------------------------------------------------------------------------
#include <eo> // eoBin, eoPop, eoLottery
//-----------------------------------------------------------------------------
typedef eoBin<float> Chrom;
void binary_value(Chrom& chrom)
{
float sum = 0;
for (unsigned i = 0; i < chrom.size(); i++)
if (chrom[i])
sum += pow(2, i);
chrom.fitness(sum);
}
//-----------------------------------------------------------------------------
main()
{
const unsigned POP_SIZE = 8, CHROM_SIZE = 4;
eoPop<Chrom> pop, pop2;
eoBinRandom<Chrom> random;
unsigned i;
for (i = 0; i < POP_SIZE; i++)
{
Chrom chrom(CHROM_SIZE);
random(chrom);
binary_value(chrom);
pop.push_back(chrom);
}
std::cout << "original population:" << std::endl;
sort(pop.begin(), pop.end());
for (i = 0; i < pop.size(); i++)
std::cout << pop[i] << " " << pop[i].fitness() << std::endl;
eoLottery<Chrom> lottery;
lottery(pop, pop2);
std::cout << "selected by lottery population:" << std::endl;
sort(pop2.begin(), pop2.end());
for (i = 0; i < pop2.size(); i++)
std::cout << pop2[i] << " " << pop2[i].fitness() << std::endl;
return 0;
}
//-----------------------------------------------------------------------------

View file

@ -0,0 +1,55 @@
//-----------------------------------------------------------------------------
// t-eoproblem.cpp
// (c) GeNeura Team 1998
//-----------------------------------------------------------------------------
#include <time.h> // time
#include <math.h> // fabs
#include <iostream> // std::cout
#include <eo> // eoVector, eoProblem
//-----------------------------------------------------------------------------
typedef eoVector<float, float> Chrom;
//-----------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const Chrom& chrom)
{
copy(chrom.begin(), chrom.end(), std::ostream_iterator<int>(os));
return os;
}
//-----------------------------------------------------------------------------
class Easy//: public eoProblem<Chrom>
{
public:
static const unsigned size;
float operator()(const Chrom& chrom)
{
return 1.0 / (fabs(chrom[0]) + 1.0);
}
};
const unsigned Easy::size = 1;
//-----------------------------------------------------------------------------
int main()
{
Easy easy;
Chrom chrom(Easy::size);
srand(time(0));
chrom[0] = ((float)rand()) / ((float)RAND_MAX);
chrom.fitness(easy(chrom));
std::cout << "chrom = " << chrom << std::endl
<< "chrom.fitness() = " << chrom.fitness() << std::endl;
return 0;
}
//-----------------------------------------------------------------------------

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;
}
//-----------------------------------------------------------------------------