included new fitness class eoScalarFitnessAssembled, that stores different fitness terms in a std::vector, but still acts as a scalar fitness. A new checkpoint uses these values for statistics.

This commit is contained in:
okoenig 2003-04-02 21:10:53 +00:00
commit b3e57bedad
8 changed files with 837 additions and 23 deletions

View file

@ -8,7 +8,7 @@ SUBDIRS = es ga gp utils other do
CPPFLAGS = -O2
lib_LIBRARIES = libeo.a
libeo_a_SOURCES = eoFunctorStore.cpp eoPersistent.cpp eoPrintable.cpp eoCtrlCContinue.cpp eoParetoFitness.cpp
libeo_a_SOURCES = eoFunctorStore.cpp eoPersistent.cpp eoPrintable.cpp eoCtrlCContinue.cpp eoParetoFitness.cpp eoScalarFitnessAssembled.cpp
libeoincdir = $(includedir)/eo
libeoinc_HEADERS = *.h eo do/*.h

View file

@ -0,0 +1,196 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- */
//-----------------------------------------------------------------------------
// make_checkpoint_assembled.h
// 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
*/
//-----------------------------------------------------------------------------
#ifndef _make_checkpoint_assembled_h
#define _make_checkpoint_assembled_h
#include <vector>
#include <string>
#include <eoScalarFitnessAssembled.h>
#include <utils/selectors.h>
#include <EO.h>
#include <eoEvalFuncCounter.h>
#include <utils/checkpointing>
// at the moment, in utils/make_help.cpp
// this should become some eoUtils.cpp with corresponding eoUtils.h
bool testDirRes(std::string _dirName, bool _erase);
/////////////////// The checkpoint and other I/O //////////////
/** Of course, Fitness needs to be an eoScalarFitnessAssembled!!! */
template <class EOT>
eoCheckPoint<EOT>& do_make_checkpoint_assembled(eoParser& _parser, eoState& _state, eoEvalFuncCounter<EOT>& _eval, eoContinue<EOT>& _continue)
{
// SOME PARSER PARAMETERS
// ----------------------
std::string dirName = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output").value();
bool erase = _parser.createParam(true, "eraseDir", "Erase files in dirName if any", '\0', "Output").value();
#if !defined(NO_GNUPLOT)
bool gnuplots = _parser.createParam(true,"plots","Plot stuff using GnuPlot",'\0',"Output").value();
#endif
bool printFile = _parser.createParam(true,"printFile","Print statistics file",'\0',"Output").value();
eoValueParam<unsigned>& saveFrequencyParam =
_parser.createParam(unsigned(0),"saveFrequency","Save every F generation (0 = only final state, absent = never)",'\0',"Persistence" );
testDirRes(dirName, erase); // TRUE
// CREATE CHECKPOINT FROM eoContinue
// ---------------------------------
eoCheckPoint<EOT> *checkpoint = new eoCheckPoint<EOT>(_continue);
_state.storeFunctor(checkpoint);
// GENERATIONS
// -----------
eoIncrementorParam<unsigned> *generationCounter = new eoIncrementorParam<unsigned>("Gen.");
_state.storeFunctor(generationCounter);
checkpoint->add(*generationCounter);
// TIME
// ----
eoTimeCounter * tCounter = NULL;
tCounter = new eoTimeCounter;
_state.storeFunctor(tCounter);
checkpoint->add(*tCounter);
// ACCESS DESCRIPTIONS OF TERMS OF FITNESS CLASS
// ---------------------------------------------
// define a temporary fitness instance
typedef typename EOT::Fitness Fit;
Fit fit;
std::vector<std::string> fitness_descriptions = fit.getDescriptionVector();
unsigned nTerms = fitness_descriptions.size();
// STAT VALUES OF A POPULATION
// ---------------------------
// average vals
std::vector<eoAverageStat<EOT>* > avgvals( nTerms );
for (unsigned i=0; i < nTerms; ++i){
std::string descr = "Avg. of " + fitness_descriptions[i];
avgvals[i] = new eoAverageStat<EOT>(i, descr);
_state.storeFunctor( avgvals[i] );
checkpoint->add( *avgvals[i] );
}
// best vals
std::vector<eoBestFitnessStat<EOT>* > bestvals( nTerms );
for (unsigned i=0; i < nTerms; ++i){
std::string descr = fitness_descriptions[i] + " of best ind.";
bestvals[i] = new eoBestFitnessStat<EOT>(i, descr);
_state.storeFunctor( bestvals[i] );
checkpoint->add( *bestvals[i] );
}
// STDOUT
// ------
eoStdoutMonitor *monitor = new eoStdoutMonitor(false);
_state.storeFunctor(monitor);
checkpoint->add(*monitor);
monitor->add(*generationCounter);
monitor->add(_eval);
monitor->add(*tCounter);
// Add best fitness
monitor->add( *bestvals[0] );
// Add all average vals
for (unsigned i=0; i < nTerms; ++i)
monitor->add( *avgvals[i] );
// GNUPLOT
// -------
#if !defined(NO_GNUPLOT)
if (gnuplots ){
std::string stmp;
// Histogramm of the different fitness vals
eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>;
_state.storeFunctor(fitStat);
checkpoint->add(*fitStat);
// a gnuplot-based monitor for snapshots: needs a dir name
eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirName);
_state.storeFunctor(fitSnapshot);
// add any stat that is a vector<double> to it
fitSnapshot->add(*fitStat);
// and of course add it to the checkpoint
checkpoint->add(*fitSnapshot);
std::vector<eoGnuplot1DMonitor*> gnumonitors(nTerms, NULL );
for (unsigned i=0; i < nTerms; ++i){
stmp = dirName + "/gnuplot_" + fitness_descriptions[i] + ".xg";
gnumonitors[i] = new eoGnuplot1DMonitor(stmp,true);
_state.storeFunctor(gnumonitors[i]);
checkpoint->add(*gnumonitors[i]);
gnumonitors[i]->add(*generationCounter);
gnumonitors[i]->add(*bestvals[i]);
gnumonitors[i]->add(*avgvals[i]);
}
}
#endif
// WRITE STUFF TO FILE
// -------------------
if( printFile ){
std::string stmp2 = dirName + "/eoStatistics.sav";
eoFileMonitor *fileMonitor = new eoFileMonitor(stmp2);
_state.storeFunctor(fileMonitor);
checkpoint->add(*fileMonitor);
fileMonitor->add(*generationCounter);
fileMonitor->add(_eval);
fileMonitor->add(*tCounter);
for (unsigned i=0; i < nTerms; ++i){
fileMonitor->add(*bestvals[i]);
fileMonitor->add(*avgvals[i]);
}
}
// STATE SAVER
// -----------
// feed the state to state savers
if (_parser.isItThere(saveFrequencyParam)) {
unsigned freq = (saveFrequencyParam.value() > 0 ? saveFrequencyParam.value() : UINT_MAX );
std::string stmp = dirName + "/generations";
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
_state.storeFunctor(stateSaver1);
checkpoint->add(*stateSaver1);
}
// and that's it for the (control and) output
return *checkpoint;
}
#endif

View file

@ -0,0 +1,41 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoScalarFitnessAssembled.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 _MSC_VER
// to avoid long name warnings
#pragma warning(disable:4786)
#endif
#include "eoScalarFitnessAssembled.h"
// need to allocate the static variables of class eoScalarFitnessAssembledTraits
std::vector<std::string> eoScalarFitnessAssembledTraits::TermDescriptions;

View file

@ -0,0 +1,221 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- */
//-----------------------------------------------------------------------------
// eoScalarFitnessAssembled.h
// 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
*/
//-----------------------------------------------------------------------------
#ifndef eoScalarFitnessAssembled_h
#define eoScalarFitnessAssembled_h
#include <functional>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <string>
//! Defines properties of eoScalarFitnessAssembled.
/*! Properties that are hold in this traits class:
- std::vector<std::string> to hold descriptions of the different fitness terms
*/
class eoScalarFitnessAssembledTraits{
public:
typedef std::vector<std::string>::size_type size_type;
static void setDescription( size_type _idx, std::string _descr ) {
if ( _idx < TermDescriptions.size() )
TermDescriptions[_idx] = _descr;
else{
TermDescriptions.resize(_idx, "Unnamed variable" );
TermDescriptions[_idx] = _descr;
}
}
static std::string getDescription( size_type _idx) {
if ( _idx < TermDescriptions.size() )
return TermDescriptions[_idx ];
else
return "Unnamed Variable";
}
static void resize( size_type _n, const std::string& _descr) {
TermDescriptions.resize(_n, _descr);
}
static size_type size() { return TermDescriptions.size(); }
static std::vector<std::string> getDescriptionVector() { return TermDescriptions; }
private:
static std::vector<std::string> TermDescriptions;
};
//! Implements fitness as std::vector, storing all values that might occur during fitness assembly
/*! Properties:
- Wraps a scalar fitness values such as a double or int, with the option of
maximizing (using less<ScalarType>) or minimizing (using greater<ScalarType>).
- Stores all kinda different values met during fitness assembly, to be defined in eoEvalFunc.
- It overrides operator<() to use the Compare template argument.
- Suitable constructors and assignments and casts are defined to work
with this quantity as if it were a ScalarType.
- Global fitness value is stored as first element in the vector
*/
template <class ScalarType, class Compare, class FitnessTraits = eoScalarFitnessAssembledTraits >
class eoScalarFitnessAssembled : public std::vector<ScalarType> {
public:
typedef typename std::vector<ScalarType>::size_type size_type;
// Basic constructors and assignments
eoScalarFitnessAssembled()
: std::vector<ScalarType>( FitnessTraits::size() ) {}
eoScalarFitnessAssembled( size_type _n,
const ScalarType& _val,
const std::string& _descr="Unnamed variable" )
: std::vector<ScalarType>(_n, _val)
{
if ( _n > FitnessTraits::size() )
FitnessTraits::resize(_n, _descr);
}
eoScalarFitnessAssembled( const eoScalarFitnessAssembled& other) : std::vector<ScalarType>( other ) {}
eoScalarFitnessAssembled& operator=( const eoScalarFitnessAssembled& other) {
std::vector<ScalarType>::operator=( other );
return *this;
}
// Constructors and assignments to work with scalar type
eoScalarFitnessAssembled( const ScalarType& v ) : std::vector<ScalarType>( 1, v ) {}
eoScalarFitnessAssembled& operator=( const ScalarType& v ) {
if ( empty() )
push_back( v );
else
front() = v;
return *this;
}
//! Overload push_back()
void push_back(const ScalarType& _val ){
std::vector<ScalarType>::push_back( _val );
if ( size() > FitnessTraits::size() )
FitnessTraits::setDescription( size()-1, "Unnamed variable");
}
//! Overload push_back()
void push_back(const ScalarType& _val, const std::string& _descr ){
std::vector<ScalarType>::push_back( _val );
FitnessTraits::setDescription( size()-1, _descr );
}
//! Overload resize()
void resize( size_type _n, const ScalarType& _val = ScalarType(), const std::string& _descr = "Unnamed variable" ){
std::vector<ScalarType>::resize(_n, _val);
FitnessTraits::resize(_n, _descr);
}
//! Set description
void setDescription( size_type _idx, std::string _descr ) {
FitnessTraits::setDescription( _idx, _descr );
}
//! Get description
std::string getDescription( size_type _idx ){ return FitnessTraits::getDescription( _idx ); }
//! Get vector with descriptions
std::vector<std::string> getDescriptionVector() { return FitnessTraits::getDescriptionVector(); }
// Scalar type access
operator ScalarType(void) const {
if ( empty() )
return 0.0;
else
return front();
}
//! Print term values and descriptions
void printAll(std::ostream& os) const {
for (size_type i=0; i < size(); ++i )
os << FitnessTraits::getDescription(i) << " = " << operator[](i) << " ";
}
// Comparison, using less by default
bool operator<(const eoScalarFitnessAssembled& other) const{
if ( empty() || other.empty() )
return false;
else
return Compare()( front() , other.front() );
}
// implementation of the other operators
bool operator>( const eoScalarFitnessAssembled<ScalarType, Compare>& y ) const { return y < *this; }
// implementation of the other operators
bool operator<=( const eoScalarFitnessAssembled<ScalarType, Compare>& y ) const { return !(*this > y); }
// implementation of the other operators
bool operator>=(const eoScalarFitnessAssembled<ScalarType, Compare>& y ) const { return !(*this < y); }
};
/**
Typedefs for fitness comparison, Maximizing Fitness compares with less,
and minimizing fitness compares with greater. This because we want ordinary
fitness values (doubles) to be equivalent with Maximizing Fitness, and
comparing with less is the default behaviour.
*/
typedef eoScalarFitnessAssembled<double, std::less<double> > eoAssembledMaximizingFitness;
typedef eoScalarFitnessAssembled<double, std::greater<double> > eoAssembledMinimizingFitness;
template <class F, class Cmp>
std::ostream& operator<<(std::ostream& os, const eoScalarFitnessAssembled<F, Cmp>& f)
{
for (unsigned i=0; i < f.size(); ++i)
os << f[i] << " ";
return os;
}
template <class F, class Cmp>
std::istream& operator>>(std::istream& is, eoScalarFitnessAssembled<F, Cmp>& f)
{
for (unsigned i=0; i < f.size(); ++i){
F value;
is >> value;
f[i] = value;
}
return is;
}
#endif

View file

@ -32,6 +32,7 @@
#include <eoFunctor.h>
#include <utils/eoParam.h>
#include <eoPop.h>
#include <eoScalarFitnessAssembled.h>
#include <eoParetoFitness.h>
/**
@ -83,10 +84,14 @@ public :
};
/**
Average fitness of a population, fitness can be a double, eoMinimizingFitness, eoMaximizingFitness or eoParetoFitness.
In the case of pareto optimization it will calculate the average of each objective.
Average fitness of a population. Fitness can be:
- double
- eoMinimizingFitness or eoMaximizingFitness
- eoScalarFitnessAssembled:
Specify in the constructor, for which fitness term (index) the average should be evaluated.
- eoParetoFitness:
The average of each objective is evaluated.
*/
#ifdef _MSC_VER
template <class EOT> class eoAverageStat : public eoStat<EOT, EOT::Fitness>
#else
@ -96,9 +101,15 @@ template <class EOT> class eoAverageStat : public eoStat<EOT, typename EOT::Fitn
public :
typedef typename EOT::Fitness fitness_type;
#ifdef _MSC_VER
eoAverageStat(std::string _description = "Average Fitness") : eoStat<EOT, EOT::Fitness>(fitness_type(), _description) {}
eoAverageStat(std::string _description = "Average Fitness")
: eoStat<EOT, EOT::Fitness>(fitness_type(), _description), whichFitnessTerm() {}
eoAverageStat(unsigned _whichTerm, std::string _description = "Average Fitness")
: eoStat<EOT, EOT::Fitness>(fitness_type(), _description), whichFitnessTerm(_whichTerm) {}
#else
eoAverageStat(std::string _description = "Average Fitness") : eoStat<EOT, typename EOT::Fitness>(fitness_type(), _description) {}
eoAverageStat(std::string _description = "Average Fitness")
: eoStat<EOT, typename EOT::Fitness>(fitness_type(), _description), whichFitnessTerm() {}
eoAverageStat(unsigned _whichTerm, std::string _description = "Average Fitness")
: eoStat<EOT, typename EOT::Fitness>(fitness_type(), _description), whichFitnessTerm(_whichTerm) {}
#endif
static fitness_type sumFitness(double _sum, const EOT& _eot)
@ -118,7 +129,8 @@ public :
#endif
}
private :
// Specialization for pareto fitness
template <class T>
void doit(const eoPop<EOT>& _pop, eoParetoFitness<T>)
{
@ -135,7 +147,23 @@ private :
value()[o] /= _pop.size();
}
}
// Specialization for eoScalarFitnessAssembled
template <class ScalarType, class Compare>
void doit(const eoPop<EOT>& _pop, eoScalarFitnessAssembled<ScalarType, Compare>)
{
if ( whichFitnessTerm >= _pop[0].fitness().size() )
throw std::logic_error("Fitness term requested out of range");
double result =0.0;
for (typename eoPop<EOT>::const_iterator it = _pop.begin(); it != _pop.end(); ++it)
result+= it->fitness()[whichFitnessTerm];
value().clear();
value() = result / _pop.size();
}
// Default behavior
template <class T>
void doit(const eoPop<EOT>& _pop, T)
{
@ -144,6 +172,8 @@ private :
value() = v / _pop.size();
}
// Store an index of the fitness term to be evaluated in eoScalarFitnessAssembled
unsigned whichFitnessTerm;
};
/**
@ -191,34 +221,38 @@ class eoNthElementFitnessStat : public eoSortedStat<EOT, typename EOT::Fitness >
public :
typedef typename EOT::Fitness Fitness;
eoNthElementFitnessStat(int _which, std::string _description = "nth element fitness") : eoSortedStat<EOT, Fitness>(Fitness(), _description), which(_which) {}
eoNthElementFitnessStat(unsigned _whichElement, std::string _description = "nth element fitness")
: eoSortedStat<EOT, Fitness>(Fitness(), _description), whichElement(_whichElement) {}
eoNthElementFitnessStat(unsigned _whichElement, unsigned _whichTerm, std::string _description = "nth element fitness")
: eoSortedStat<EOT, Fitness>(Fitness(), _description), whichElement(_whichElement), whichFitnessTerm(_whichTerm) {}
virtual void operator()(const std::vector<const EOT*>& _pop)
{
if (which > _pop.size())
if (whichElement > _pop.size())
throw std::logic_error("fitness requested of element outside of pop");
doit(_pop, Fitness());
}
private :
struct CmpFitness
{
CmpFitness(unsigned _which, bool _maxim) : which(_which), maxim(_maxim) {}
CmpFitness(unsigned _whichElement, bool _maxim) : whichElement(_whichElement), maxim(_maxim) {}
bool operator()(const EOT* a, const EOT* b)
{
if (maxim)
return a->fitness()[which] > b->fitness()[which];
return a->fitness()[whichElement] > b->fitness()[whichElement];
return a->fitness()[which] < b->fitness()[which];
return a->fitness()[whichElement] < b->fitness()[whichElement];
}
unsigned which;
unsigned whichElement;
bool maxim;
};
// Specialization for eoParetoFitness
template <class T>
void doit(const eoPop<EOT>& _pop, eoParetoFitness<T>)
{
@ -231,21 +265,31 @@ private :
for (unsigned o = 0; o < value().size(); ++o)
{
typename std::vector<const EOT*>::iterator nth = tmp_pop.begin() + which;
typename std::vector<const EOT*>::iterator nth = tmp_pop.begin() + whichElement;
std::nth_element(tmp_pop.begin(), nth, tmp_pop.end(), CmpFitness(o, traits::maximizing(o)));
value()[o] = (*nth)->fitness()[o];
}
}
// Specialization for eoScalarFitnessAssembled
template <class ScalarType, class Compare>
void doit(const eoPop<EOT>& _pop, eoScalarFitnessAssembled<ScalarType, Compare>)
{
if ( whichFitnessTerm >= _pop[0].fitness().size() )
throw std::logic_error("Fitness term requested out of range");
value().clear();
value() = _pop[whichElement]->fitness()[whichFitnessTerm];
}
// for everything else
template <class T>
void doit(const std::vector<const EOT*>& _pop, T)
{
value() = _pop[which]->fitness();
value() = _pop[whichElement]->fitness();
}
unsigned which;
unsigned whichElement;
unsigned whichFitnessTerm;
};
/* Actually, you shouldn't need to sort the population to get the best fitness
@ -273,8 +317,15 @@ public :
*/
/**
Best fitness in the population
Best fitness of a population. Fitness can be:
- double
- eoMinimizingFitness or eoMaximizingFitness
- eoScalarFitnessAssembled:
Best individual is found according to its fitness,
specify in the constructor which fitness term of this individual should then be stored.
- eoParetoFitness:
*/
#ifdef _MSC_VER
template <class EOT>
class eoBestFitnessStat : public eoStat<EOT, EOT::Fitness>
@ -286,7 +337,10 @@ class eoBestFitnessStat : public eoStat<EOT, typename EOT::Fitness>
public :
typedef typename EOT::Fitness Fitness;
eoBestFitnessStat(std::string _description = "Best ") : eoStat<EOT, Fitness>(Fitness(), _description) {}
eoBestFitnessStat(std::string _description = "Best ")
: eoStat<EOT, Fitness>(Fitness(), _description) {}
eoBestFitnessStat(unsigned _whichTerm, std::string _description = "Best ")
: eoStat<EOT, Fitness>(Fitness(), _description), whichFitnessTerm(_whichTerm) {}
void operator()(const eoPop<EOT>& _pop)
{
@ -311,7 +365,7 @@ private :
bool maxim;
};
// Specialization for pareto fitness
template <class T>
void doit(const eoPop<EOT>& _pop, eoParetoFitness<T>)
{
@ -324,7 +378,17 @@ private :
value()[o] = it->fitness()[o];
}
}
// Specialization for eoScalarFitnessAssembled
template <class ScalarType, class Compare>
void doit(const eoPop<EOT>& _pop, eoScalarFitnessAssembled<ScalarType, Compare>){
if ( whichFitnessTerm >= _pop[0].fitness().size() )
throw std::logic_error("Fitness term requested out of range");
value().clear();
value() = _pop.best_element().fitness()[whichFitnessTerm];
}
// default
template<class T>
void doit(const eoPop<EOT>& _pop, T)
@ -332,6 +396,7 @@ private :
value() = _pop.best_element().fitness();
}
unsigned whichFitnessTerm;
};
template <class EOT>

View file

@ -4,6 +4,8 @@
##
###############################################################################
CLEANFILES = *~ *.sav *.status
DEPS = $(top_builddir)/src/utils/libeoutils.a $(top_builddir)/src/libeo.a
###############################################################################
@ -15,7 +17,7 @@ CXXFLAGS = -g -Wall
# 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
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
#The run_tests script can be used to check various arguments
TESTS=$(check_PROGRAMS) run_tests
@ -175,3 +177,17 @@ t_eoPBIL_LDFLAGS = -lm
t_eoPBIL_LDADD = $(top_builddir)/src/ga/libga.a $(LDADDS)
###############################################################################
t_eoFitnessAssembled_SOURCES = t-eoFitnessAssembled.cpp
t_eoFitnessAssembled_DEPENDENCIES = $(DEPS) $(top_builddir)/src/ga/libga.a
t_eoFitnessAssembled_LDFLAGS = -lm
t_eoFitnessAssembled_LDADD = $(top_builddir)/src/ga/libga.a $(LDADDS)
###############################################################################
t_eoFitnessAssembledEA_SOURCES = t-eoFitnessAssembledEA.cpp
t_eoFitnessAssembledEA_DEPENDENCIES = $(DEPS) $(top_builddir)/src/es/libes.a
t_eoFitnessAssembledEA_LDFLAGS = -lm
t_eoFitnessAssembledEA_LDADD = $(top_builddir)/src/es/libes.a $(LDADDS)
###############################################################################

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,170 @@
// -*- 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
*/
//-----------------------------------------------------------------------------
#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;
}