move paradiseo/eo to deprecated/ before merge with eodev

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

View file

@ -0,0 +1,38 @@
######################################################################################
### 1) Include the sources
######################################################################################
INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
######################################################################################
### 2) Specify where CMake can find the libraries (mandatory: before 3) )
######################################################################################
LINK_DIRECTORIES(${EO_BINARY_DIR}/lib)
######################################################################################
### 3) Define your target(s): just an executable here
######################################################################################
SET (GPSYMREG_SOURCES main.cpp)
# no matter what is the OS, hopefully
ADD_EXECUTABLE(gpsymreg ${GPSYMREG_SOURCES})
ADD_DEPENDENCIES(gpsymreg eo eoutils)
######################################################################################
### 4) Optionnal: define your target(s)'s version: no effect for windows
######################################################################################
SET(GPSYMREG_VERSION ${GLOBAL_VERSION})
SET_TARGET_PROPERTIES(gpsymreg PROPERTIES VERSION "${GPSYMREG_VERSION}")
######################################################################################
### 5) Link the librairies for your target(s)
######################################################################################
TARGET_LINK_LIBRARIES(gpsymreg eo eoutils)
######################################################################################

View file

@ -0,0 +1,227 @@
/*
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 General Public License
along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
jeggermo@liacs.nl
*/
#ifndef _FITNESS_FUNCTION_H
#define _FITNESS_FUNCTION_H
#include <gp/eoParseTree.h>
#include <eo>
#include <cmath>
#include "parameters.h"
#include "node.h"
using namespace gp_parse_tree;
using namespace std;
// the first fitness is the normal goal fitness
// the second fitness is the tree size (we prefer smaller trees)
// lets use names to define the different fitnesses
#define NORMAL 0 // Stepwise Adaptation of Weights Fitness
#define SMALLESTSIZE 1 // The size of the tree, we want to minimize this one -- statistics will tell us the smallest tree size
// Look: overloading the maximization without overhead (thing can be inlined)
class MinimizingFitnessTraits : public eoParetoFitnessTraits
{
public :
static bool maximizing(int which) { return false;} // we want to minimize both fitnesses
static unsigned nObjectives() { return 2;} // the number of fitnesses }
};
// Lets define our MultiObjective FitnessType
typedef eoParetoFitness<MinimizingFitnessTraits> FitnessType;
// John Koza's sextic polynomial (our example problem)
double sextic_polynomial(double x)
{
double result=0;
result = pow(x,6) - (2*pow(x,4)) + pow(x,2);
return result;
}
// we use the following functions for the basic math functions
double _plus(double arg1, double arg2)
{
return arg1 + arg2;
}
double _minus(double arg1, double arg2)
{
return arg1 - arg2;
}
double _multiplies(double arg1, double arg2)
{
return arg1 * arg2;
}
// the function for a protected divide looks a little bit different
double _divides(double arg1, double arg2)
{
if (arg2 ==0)
return 0;
else
return arg1 / arg2;
}
double _negate(double arg1)
{
return -arg1;
}
// now let's define our tree nodes
void init(vector<Node> &initSequence)
{
// we have only one variable (X)
Operation varX( (unsigned int) 0, string("X") );
// the main binary operators
Operation OpPLUS ( _plus, string("+"));
Operation OpMINUS( _minus,string("-"));
Operation OpMULTIPLIES(_multiplies,string("*"));
// We can use a protected divide function.
Operation OpDIVIDE( _divides, string("/") );
// Now the functions as binary functions
Operation PLUS( string("plus"), _plus);
Operation MINUS( string("minus"), _minus);
Operation MULTIPLIES( string("multiply"), _multiplies);
Operation DIVIDE( string("divide"), _divides);
// and some unary functions
Operation NEGATE( _negate,string("-"));
Operation SIN ( sin, string("sin"));
Operation COS ( cos, string("cos"));
// Now we are ready to add the possible nodes to our initSequence (which is used by the eoDepthInitializer)
// so lets start with our variable
initSequence.push_back(varX);
// followed by the constants 2, 4, 6
for(unsigned int i=2; i <= 6; i+=2)
{
char text[255];
sprintf(text, "%i", i);
Operation op(i*1.0, text);
initSequence.push_back( op );
// and we add the variable again (so we have get lots of variables);
initSequence.push_back( varX );
}
// next we add the unary functions
initSequence.push_back( NEGATE );
initSequence.push_back( SIN );
initSequence.push_back( COS );
// and the binary functions
initSequence.push_back( PLUS);
initSequence.push_back( MINUS );
initSequence.push_back( MULTIPLIES );
initSequence.push_back( DIVIDE );
// and the binary operators
initSequence.push_back( OpPLUS);
initSequence.push_back( OpMINUS );
initSequence.push_back( OpMULTIPLIES );
initSequence.push_back( OpDIVIDE );
}
class RegFitness: public eoEvalFunc< eoParseTree<FitnessType, Node> >
{
public:
typedef eoParseTree<FitnessType, Node> EoType;
void operator()(EoType &_eo)
{
vector< double > input(1); // the input variable(s)
double output(0.);
double target;
FitnessType fitness;
float x=0;
double fit=0;
for(x=-1; x <= 1; x+=0.1)
{
input[0] = x;
target = sextic_polynomial(x);
_eo.apply(output,input);
fit += pow(target - output, 2);
}
fitness[NORMAL] = fit;
fitness[SMALLESTSIZE] = _eo.size() / (1.0*parameter.MaxSize);
_eo.fitness(fitness);
if (fitness[NORMAL] < best[NORMAL])
{
best[NORMAL] = fitness[NORMAL];
tree="";
_eo.apply(tree);
}
}
RegFitness(eoValueParam<unsigned> &_generationCounter, vector< Node > &initSequence, Parameters &_parameter) : eoEvalFunc<EoType>(), generationCounter(_generationCounter), parameter(_parameter)
{
init(initSequence);
best[NORMAL] = 1000;
tree= "not found";
};
~RegFitness()
{
cerr << "Best Fitness= " << best[NORMAL] << endl;
cerr << tree << endl;
};
private:
eoValueParam<unsigned> &generationCounter; // so we know the current generation
Parameters &parameter; // the parameters
FitnessType best; // the best found fitness
string tree;
};
#endif

View file

@ -0,0 +1,337 @@
/*
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 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 General Public License
along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
jeggermo@liacs.nl
*/
#ifdef _MSC_VER
#pragma warning(disable:4786)
#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include "gp/eoParseTree.h"
#include "eo"
using namespace gp_parse_tree;
using namespace std;
//-----------------------------------------------------------------------------
#include "node.h"
#include "parameters.h"
#include "fitness.h"
// TYPE DECLARATIONS FOR GP
typedef eoParseTree<FitnessType, Node > EoType;
typedef eoPop<EoType> Pop;
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
// the vector containing the possible nodes
vector<Node> initSequence;
// initialise parameters
Parameters parameter(argc, argv);
// set the randomseed
rng.reseed(parameter.randomseed);
// Create a generation counter
eoValueParam<unsigned> generationCounter(0, "Gen.");
// Create an incrementor (sub-class of eoUpdater). Note that the
// parameter's value is passed by reference,
// so every time the incrementer is updated (every generation),
// the data in generationCounter will change.
eoIncrementor<unsigned> increment(generationCounter.value());
// create an instantiation of the fitness/evaluation function
// it initializes the initSequence vector
// the parameters are passed on as well
RegFitness eval(generationCounter, initSequence, parameter);
// Depth Initializor, set for Ramped Half and Half Initialization
eoParseTreeDepthInit<FitnessType, Node> initializer(parameter.InitMaxDepth, initSequence, true, true);
// create the initial population
Pop pop(parameter.population_size, initializer);
// and evaluate the individuals
apply<EoType>(eval, pop);
generationCounter.value()++; // set the generationCounter to 1
// define X-OVER
eoSubtreeXOver<FitnessType, Node> xover(parameter.MaxSize);
// define MUTATION
eoBranchMutation<FitnessType, Node> mutation(initializer, parameter.MaxSize);
// eoExpansionMutation<FitnessType, Node> mutation(initializer, parameter.MaxSize);
// eoCollapseSubtreeMutation<FitnessType, Node> mutation(initializer, parameter.MaxSize);
// eoPointMutation<FitnessType, Node> mutation(initSequence);
// eoHoistMutation<FitnessType, Node> mutation;
// The operators are encapsulated into an eoTRansform object,
// that performs sequentially crossover and mutation
eoSGATransform<EoType> transform(xover, parameter.xover_rate, mutation, parameter.mutation_rate);
// The robust tournament selection
// in our case 5-tournament selection
eoDetTournamentSelect<EoType> selectOne(parameter.tournamentsize);
// is now encapsulated in a eoSelectMany
eoSelectMany<EoType> select(selectOne, parameter.offspring_size, eo_is_an_integer);
// and the generational replacement
//eoGenerationalReplacement<EoType> replace;
// or the SteadtState replacment
//eoSSGAWorseReplacement<EoType> replace;
// or comma selection
eoCommaReplacement<EoType> replace;
// Terminators
eoGenContinue<EoType> term(parameter.nGenerations);
eoCheckPoint<EoType> checkPoint(term);
// STATISTICS
eoAverageStat<EoType> avg;
eoBestFitnessStat<EoType> best;
// Add it to the checkpoint,
// so the counter is updated (here, incremented) every generation
checkPoint.add(increment);
checkPoint.add(avg);
checkPoint.add(best);
#ifdef HAVE_GNUPLOT
eoGnuplot1DMonitor gnuplotmonitor("gnuplotBestStats");
gnuplotmonitor.add(generationCounter);
gnuplotmonitor.add(best);
// we need to add a empty string variable if we want to seed the second fitness value
eoValueParam<string> dummy1("", "Smallest Tree Size");
gnuplotmonitor.add(dummy1);
eoGnuplot1DMonitor gnuplotAvgmonitor("gnuplotAvgStats");
gnuplotAvgmonitor.add(generationCounter);
gnuplotAvgmonitor.add(avg);
// we need to add a empty string variable if we want to seed the second fitness value
eoValueParam<string> dummy2("", "Average Tree Size");
gnuplotAvgmonitor.add(dummy2);
checkPoint.add(gnuplotmonitor);
checkPoint.add(gnuplotAvgmonitor);
#endif
// GP Generation
eoEasyEA<EoType> gp(checkPoint, eval, select, transform, replace);
cout << "Initialization done" << endl;
try
{
gp(pop);
}
catch (exception& e)
{
cout << "exception: " << e.what() << endl;;
exit(EXIT_FAILURE);
}
return 1;
}

View file

@ -0,0 +1,248 @@
/*
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 General Public License
along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
jeggermo@liacs.nl
*/
#ifndef _NODE_H
#define _NODE_H
#include <iostream>
#include <string>
#include <cmath> // for finite(double) function
using namespace gp_parse_tree;
using namespace std;
/* A new Operation and Node class for even more flexibility.
Improvements over the t-eoSymreg code are:
* No hardcoded functions or operators. The Operation and Node class below
allow you to specify your own unary and binary functions as well as
binary operators (like +,-,*,/). Moreover you can detemine if you want
to allow primitve subroutines with either one or two arguments.
If a Node has a subroutine Operation it will take evaluate the first
(and possible second) child branch and use them as input variables for
the remaining second (or third) child branch.
*/
typedef enum {Variable, UFunction, BFunction, BOperator, Const} Type;
typedef double (*BinaryFunction)(const double,const double);
typedef double (*UnaryFunction)(const double);
struct Operation
{
public:
typedef unsigned int VariableID;
typedef string Label;
// if your compiler allows you to have nameless unions you can make this a
// union by removing the //'s below
//union
//{
UnaryFunction uFunction;
BinaryFunction bFunction;
VariableID id;
double constant;
//};
Label label;
Type type;
// the default constructor results in a constant with value 0
Operation() : constant(0), label("0"), type(Const){};
// two possible constructors for Unary Functions
Operation(UnaryFunction _uf, Label _label): uFunction(_uf), label(_label), type(UFunction) {};
Operation(Label _label, UnaryFunction _uf): uFunction(_uf), label(_label), type(UFunction) {};
// Watch out there are two constructors using pointers two binary functions:
// Binary Function (printed as label(subtree0,subtree1) (e.g. pow(x,y))
// Binary Operator (printed as (subtree0 label subtree1) (e.g. x^y)
// The difference is purely cosmetic.
// If you specify the label before the function pointer -> Binary Function
Operation(Label _label, BinaryFunction _bf): bFunction(_bf), label(_label), type(BFunction) {};
// If you specify the function pointer before the label -> Binary Operator
Operation(BinaryFunction _bf, Label _label): bFunction(_bf), label(_label), type(BOperator) {};
// A constructor for variables
Operation(VariableID _id, Label _label): id(_id), label(_label), type(Variable) {};
// A constructor for constants
Operation(double _constant, Label _label): constant(_constant), label(_label), type(Const) {};
Operation(const Operation &_op)
{
switch(_op.type)
{
case Variable: id = _op.id; break;
case UFunction: uFunction = _op.uFunction; break;
case BFunction: bFunction = _op.bFunction; break;
case BOperator: bFunction = _op.bFunction; break;
case Const: constant = _op.constant; break;
}
type = _op.type;
label = _op.label;
};
virtual ~Operation(){};
};
class Node
{
private:
Operation op;
public:
Node(void): op(Operation()){};
Node(Operation &_op) : op(_op){};
virtual ~Node(void) {}
int arity(void) const
{
switch(op.type)
{
case Variable: return 0;
case UFunction: return 1;
case BFunction: return 2;
case BOperator: return 2;
case Const: return 0;
}
return 0;
}
void randomize(void) {}
template<class Children>
void operator()(double& result, Children args, vector<double> &var) const
{
double result0;
double result1;
switch(op.type)
{
case Variable: result = var[op.id%var.size()]; //%var.size() used in the case of Subroutines and as a security measure
break;
case UFunction: args[0].apply(result0, var);
result = op.uFunction(result0);
break;
case BFunction:
case BOperator: args[0].apply(result0, var);
args[1].apply(result1, var);
result = op.bFunction(result0,result1);
break;
case Const: result = op.constant;
break;
}
}
template<class Children>
void operator()(string& result, Children args) const
{
string subtree0;
string subtree1;
string subtree2;
switch(op.type)
{
case Variable:
case Const: result += op.label;
break;
case UFunction: result += op.label;
result += "(";
args[0].apply(subtree0);
result += subtree0;
result += ")";
break;
case BFunction: result += op.label;
result += "(";
args[0].apply(subtree0);
result += subtree0;
result += ",";
args[1].apply(subtree1);
result += subtree1;
result += ")";
break;
case BOperator: result += "(";
args[0].apply(subtree0);
result += subtree0;
result += op.label;
args[1].apply(subtree1);
result += subtree1;
result += ")";
break;
default: result += "ERROR in Node::operator(string,...) \n"; break;
}
}
Operation getOp(void) const {return op;}
};
//-----------------------------------------------------------
// saving, loading LETS LEAVE IT OUT FOR NOW
std::ostream& operator<<(std::ostream& os, const Node& eot)
{
Operation op(eot.getOp());
os << (eot.getOp()).label;
return os;
}
// we can't load because we are using function pointers. Instead we prevent a compiler warning by calling the arity() function.
std::istream& operator>>(std::istream& is, Node& eot)
{
eot.arity();
return is;
}
#endif

View file

@ -0,0 +1,112 @@
/*
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 General Public License
along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
jeggermo@liacs.nl
*/
#ifndef _PARAMETERS_FUNCTION_H
#define _PARAMETERS_FUNCTION_H
#include <gp/eoParseTree.h>
#include <eo>
using namespace gp_parse_tree;
using namespace std;
struct Parameters{
unsigned int nGenerations; // -G
unsigned population_size; // -P
unsigned offspring_size; // -O
unsigned int MaxSize; // -S
unsigned int InitMaxDepth; // -D
unsigned int randomseed; // -R
double xover_rate; // -x
double mutation_rate; // -y
unsigned int tournamentsize; // -t
Parameters(int argc, char **argv)
{
eoParser parser(argc,argv);
// generations
eoValueParam<unsigned int> paramGenerations(1, "generations", "Generations", 'G', false);
parser.processParam( paramGenerations );
nGenerations = paramGenerations.value();
cerr << "nGenerations= " << nGenerations << endl;
// populationsize
eoValueParam<unsigned int> paramPopulationSize(10, "populationsize", "PopulationSize", 'P', false);
parser.processParam( paramPopulationSize );
population_size = paramPopulationSize.value();
cerr << "population_size= " << population_size << endl;
// offspringsize
eoValueParam<unsigned int> paramOffspringSize(population_size, "offspringsize", "OffspringSize", 'O', false);
parser.processParam( paramOffspringSize );
offspring_size = paramOffspringSize.value();
cerr << "offspring_size= " << offspring_size << endl;
// maxsize
eoValueParam<unsigned int> paramMaxSize(15, "maxsize", "MaxSize", 'S', false);
parser.processParam( paramMaxSize );
MaxSize = paramMaxSize.value();
cerr << "MaxSize= " << MaxSize << endl;
// initialmaxdepth
eoValueParam<unsigned int> paramInitialMaxDepth(4, "initialmaxdepth", "InitialMaxDepth", 'D', false);
parser.processParam( paramInitialMaxDepth );
InitMaxDepth = paramInitialMaxDepth.value();
cerr << "InitMaxDepth= " << InitMaxDepth << endl;
// randomseed
eoValueParam<unsigned int> paramRandomSeed(1, "randomseed", "Random Seed", 'R', false);
parser.processParam( paramRandomSeed );
randomseed = paramRandomSeed.value();
cerr << "randomseed= " << randomseed << endl;
// crossover-rate
eoValueParam<double> paramXover(0.75, "crossoverrate", "crossover rate", 'x', false);
parser.processParam(paramXover );
xover_rate = paramXover.value();
cerr << "xover_rate= " << xover_rate << endl;
//mutation-rate
eoValueParam<double> paramMutation(0.25, "mutationrate", "mutation rate", 'm', false);
parser.processParam(paramMutation );
mutation_rate = paramMutation.value();
cerr << "mutation_rate= " << mutation_rate << endl;
//tournament size
eoValueParam<unsigned int > paramTournamentSize(5, "tournamentsize", "tournament size", 't', false);
parser.processParam(paramTournamentSize );
tournamentsize = paramTournamentSize.value();
cerr << "Tournament Size= " << tournamentsize << endl;
if (parser.userNeedsHelp())
{
parser.printHelp(cout);
exit(1);
}
};
~Parameters(){};
};
#endif