This commit is contained in:
gustavo 1999-01-29 12:23:55 +00:00
commit 3fe0218a72
79 changed files with 12547 additions and 0 deletions

6
eo/src/.cvsignore Normal file
View file

@ -0,0 +1,6 @@
*.lo
*.la
.deps
.libs
Makefile
Makefile.in

123
eo/src/EO.h Normal file
View file

@ -0,0 +1,123 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// EO.h
// (c) GeNeura Team 1998
//-----------------------------------------------------------------------------
#ifndef EO_H
#define EO_H
//-----------------------------------------------------------------------------
#include <stdexcept> // runtime_error
#include <eoObject.h>
#include <eoPersistent.h>
//-----------------------------------------------------------------------------
/** EO is a base class for evolvable objects, that is, the subjects of evolution.
EOs have only got a fitness, which at the same time needs to be only an object with the
operation less than (<) defined. Fitness says how good is the object; evolution or change
of these objects is left to the genetic operators. A fitness less than another means a
worse fitness, in whatever the context; thus, fitness is always maximized; although
it can be minimized with a proper definition of the < operator.\\
The fitness object must have, besides an void ctor, a copy ctor.
*/
template<class F> class EO: public eoObject, public eoPersistent
{
public:
typedef F Fitness;
/** Default constructor.
Fitness must have a ctor which takes 0 as a value; we can not use void ctors here
since default types like float have no void initializer. VC++ allows it, but gcc does not
*/
EO(): repFitness(0), invalidFitness(true) {}
/** Ctor from stream.
Fitness must have defined the lecture from an istream.
*/
EO( istream& _is ) {
_is >> repFitness;
validFitness = true;
};
/// Copy ctor
EO( const EO& _eo ): repFitness( _eo.repFitness ), invalidFitness( _eo.invalidFitness ) {};
/// Virtual dtor
virtual ~EO() {};
/// Return fitness value.
Fitness fitness() const
{
if (invalid())
throw runtime_error("invalid fitness");
return repFitness;
}
// Set fitness as invalid.
void invalidate() { invalidFitness = true; }
/** Set fitness. At the same time, validates it.
* @param _fitness New fitness value.
*/
void fitness(const Fitness& _fitness)
{
repFitness = _fitness;
invalidFitness = false;
}
/** Return true If fitness value is invalid, false otherwise.
* @return true If fitness is invalid.
*/
bool invalid() const { return invalidFitness; }
/// Methods inherited from eoObject
//@{
/** Return the class id.
* @return the class name as a string
*/
virtual string className() const { return "EO"; };
/**
* Read object.\\
* Calls base class, just in case that one had something to do. The read and print
* methods should be compatible and have the same format. In principle, format is
* "plain": they just print a number
* @param _is a istream.
* @throw runtime_exception If a valid object can't be read.
*/
virtual void readFrom(istream& _is) {
_is >> repFitness;
invalidFitness = false;
}
/**
* Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream.
*/
virtual void printOn(ostream& _os) const {
_os << repFitness << endl;
}
//@}
private:
Fitness repFitness; // value of fitness for this chromosome
bool invalidFitness; // true if the value of fitness is invalid
};
//-----------------------------------------------------------------------------
template<class T> bool operator<(const EO<T>& eo1, const EO<T>& eo2)
{
return eo1.fitness() < eo2.fitness();
}
//-----------------------------------------------------------------------------
#endif EO_H

10
eo/src/Makefile.am Normal file
View file

@ -0,0 +1,10 @@
###############################################################################
##
## Makefile.am for eo/src
##
###############################################################################
lib_LTLIBRARIES = libeo.la
libeo_la_SOURCES = eoObject.cpp eoPersistent.cpp eoPrintable.cpp
libeoincdir = $(includedir)/eo
libeoinc_HEADERS = eo EO.h eoDup.h eoMultiMonOp.h eoPop.h eoUniform.h eoESChrom.h eoNegExp.h eoProblem.h eoVector.h eoFitness.h eoNormal.h eoRnd.h eoXOver2.h eo1d.h eoID.h eoObject.h eoString.h eoAged.h eoKill.h eoOp.h eoTranspose.h eoBin.h

50
eo/src/eo Normal file
View file

@ -0,0 +1,50 @@
//-----------------------------------------------------------------------------
// eo
// (c) GeNeura Team 1998
//-----------------------------------------------------------------------------
#ifndef _eo_
#define _eo_
//-----------------------------------------------------------------------------
#include <eoObject.h>
#include <eoPrintable.h>
#include <eoPersistent.h>
#include <EO.h>
#include <eoID.h>
#include <eoAged.h>
#include <eoVector.h>
#include <eo1d.h>
#include <eoString.h>
#include <eoESChrom.h>
#include <eoBin.h>
#include <eoRnd.h>
#include <eoUniform.h>
#include <eoNormal.h>
#include <eoNegExp.h>
#include <eoOp.h>
#include <eoMultiMonOp.h>
#include <eoDup.h>
#include <eoKill.h>
#include <eoTranspose.h>
#include <eoXOver2.h>
#include <eoMutation.h>
#include <eoPop.h>
#include <eoPopOps.h>
#include <eoFitness.h> // what's the matter with you?
#include <eoProblem.h> // what's the matter with you?
//#include <eoGA.h>
//-----------------------------------------------------------------------------
#endif _eo_

164
eo/src/eo1d.h Normal file
View file

@ -0,0 +1,164 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eo1d.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EO1D_H
#define _EO1D_H
#include <iostream> // for ostream
// EO Includes
#include <EO.h>
#include <eoRnd.h>
using namespace std;
/** @name EO1d class
* Randomly accesible evolvable object with one dimension, with
variable length.
* Use this if you want to evolve "linear" things, like bitstrings, or
floating-point arrays. If you don't, subclass directly from EO
* @see EO
* @author GeNeura
* @version 0.2
*/
//@{
/** eo1d: Base class for "chromosomes" with a single dimension
#T# is the type it will be instantiated with; this type must have, at
least, a copy ctor, assignment operators,
*/
template<class T, class fitnessT = float>
class eo1d: public EO< fitnessT > {
public:
/// Declaration to make it accessible from subclasses
typedef T Type;
/** Can be used as default ctor; should be called from derived
classes. Fitness should be at birth
*/
eo1d()
:EO<fitnessT> ( ) {};
/** Ctor using a random number generator and with an specified size
@param _rndGen Random number generator
@param _size lineal dimension of the eo1d
@param _ID An ID string, preferably unique
*/
eo1d( unsigned _size, eoRnd<T>& _rndGen, const string& _ID = "");
/** Ctor from a istream. It just passes the stream to EO.
@param _is the input stream; eo1d just cares about the fitness
*/
eo1d( istream& _is): EO<fitnessT>( _is ){};
/// Copy ctor
eo1d( const eo1d& _eo )
:EO<fitnessT> ( _eo ) {};
/// Assignment operator
const eo1d& operator= ( const eo1d& _eo ) {
EO<fitnessT>::operator = ( _eo );
return *this;
}
/// Needed virtual dtor
virtual ~eo1d(){};
/** Reads and returns a copy of the gene in position _i
This implies that T must have a copy ctor .
@param _i index of the gene, which is the minimal unit. Must be
an unsigned less than #length()#
@return what's inside the gene, with the correct type
@exception out_of_range if _i > size()
*/
virtual T gene( unsigned _i ) const = 0;
/** Overwrites the gene placed in position _i with a
* new value. This means that the assignment operator
* for T must be defined .
@param _i index
@return what's inside the gene, with the correct type
@exception out_of_range if _i > size()
*/
virtual T& gene( unsigned _i ) = 0;
/** Inserts a gene, moving the rest to the right. If
* _i = length(), it should insert it at the end.
* Obviously, changes length
@param _i index
@param _val new value
*/
virtual void insertGene( unsigned _i, T _val ) = 0;
/** Eliminates the gene at position _i; all the other genes will
be shifted left
@param _i index of the gene that is going to be modified.
*/
virtual void deleteGene( unsigned _i ) = 0;
/// Returns the number of genes in the eo1d
virtual unsigned length() const = 0;
/// @name Methods from eoObject
//@{
/**
* Read object. Theoretically, the length is known in advance. All objects
* Should call base class
* @param _s A istream.
* @throw runtime_exception If a valid object can't be read.
*/
virtual void readFrom(istream& _s) {
for ( unsigned i = 0; i < length(); i ++ ) {
_s >> gene( i );
}
// there is no way of distinguishing fitness from the object, so
// it's skipped
}
/** Print itself: inherited from eoObject implementation. Declared virtual so that
it can be reimplemented anywhere. Instance from base classes are processed in
base classes, so you don´t have to worry about, for instance, fitness.
@param _s the ostream in which things are written*/
virtual void printOn( ostream& _s ) const{
for ( unsigned i = 0; i < length(); i ++ ) {
_s << gene( i ) << " ";
}
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eo1d";};
//@}
};
//@}
// --------------- Implementations --------------------------
/* Ctor using a random number generator and with an specified size
@param _rndGen Random number generator
@param _size lineal dimension of the eo1d
@param _ID An ID string, preferably unique
*/
template< class T, class fitnessT>
eo1d<T,fitnessT>::eo1d<T,fitnessT>( unsigned _size, eoRnd<T>& _rndGen,
const string& _ID )
:EO<fitnessT> ( _ID ) {
for ( unsigned i = 0; i < size; i ++ ) {
insertGene( i, _rndGen() );
}
};
#endif

90
eo/src/eoAged.h Normal file
View file

@ -0,0 +1,90 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoAge.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef EOAGED_H
#define EOAGED_H
//-----------------------------------------------------------------------------
#include <iostream> // istream, ostream
#include <string> // para string
using namespace std;
//-----------------------------------------------------------------------------
// eoAge
//-----------------------------------------------------------------------------
/** eoAge is a template class that adds an age to an object.\\
Requisites for template instantiation are that the object must admit a default ctor
and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className,
printOn, readFrom.
@see eoObject
*/
template <class Object>
class eoAged: public Object
{
public:
/// Main ctor from an already built Object.
eoAged( const Object& _o): Object( _o ), age(0) {};
/// Copy constructor.
eoAged( const eoAged& _a): Object( _a ), age( _a.age ) {};
/// Virtual dtor. They are needed in virtual class hierarchies
virtual ~eoAged() {};
///returns the age of the object
unsigned long Age() const {return age;}
/// Increments age
const eoAged& operator ++ () { age++; return *this;}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d
*/
//@{
/** Return the class id. This should be redefined in each class; but
it's got code as an example of implementation. Only "leaf" classes
can be non-virtual.
*/
virtual string className() const { return string("eoAged")+Object::className(); };
/**
* Read object.
* @param _is A istream.
* @throw runtime_exception If a valid object can't be read.
*/
virtual void readFrom(istream& _is) {
Object::readFrom( _is );
_is >> age;
}
/**
* Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream.
*/
virtual void printOn(ostream& _os) const{
Object::printOn( _os );
_os << age;
}
//@}
private:
/** Default Constructor. \\
It´s private so that it is not used anywhere; the right way of using this object
is to create an Object and passing it to an aged by means of the copy ctor; that way
it´s turned into an Aged object*/
eoAged(): Object(), age(0) {};
unsigned long age;
};
#endif EOAGE_H

387
eo/src/eoBin.h Normal file
View file

@ -0,0 +1,387 @@
//-----------------------------------------------------------------------------
// eoBin.h
//-----------------------------------------------------------------------------
#ifndef eoBin_h
#define eoBin_h
//-----------------------------------------------------------------------------
#include <iostream> // ostream, istream
#include <bvector.h> // bit_vector
#include <string> // string
#include <EO.h> // EO
#include <eoOp.h> // eoMonOp
#include <eoUniform.h> // eoUniform
#include <eoRnd.h> // eoRnd
//-----------------------------------------------------------------------------
template <class F> class eoBin: public EO<F>, public bit_vector
{
public:
typedef bool Type;
/// (Default) Constructor.
/// @param size Size of the binary string.
eoBin(const unsigned& size = 0, const bool& value = false):
bit_vector(size, value) {}
/// (Default) Constructor.
/// @param size Size of the binary string.
eoBin(const unsigned& size, const eoRnd<Type>& rnd): bit_vector(size)
{
generate(begin(), end(), rnd);
}
/// Constructor from istream.
/// @param is The istream to read from.
eoBin(istrstream& is)
{
readFrom(is);
}
/// My class name.
string className() const
{
return "eoBin";
}
/// To print me on a stream.
/// @param os The ostream.
void printOn(ostream& os) const
{
copy(begin(), end(), ostream_iterator<bool>(os));
}
/// To read me from a stream.
/// @param is The istream.
void readFrom(istream& is)
{
string bits;
is >> bits;
if (is)
{
resize(bits.size());
transform(bits.begin(), bits.end(), begin(),
bind2nd(equal_to<char>(), '1'));
}
}
};
//-----------------------------------------------------------------------------
// eoBinRandom --> mofify a chromosome in a random way
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinRandom: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinRandom"; }
///
void operator()(Chrom& chrom) const
{
eoUniform<float> uniform(0.0, 1.0);
for (unsigned i = 0; i < chrom.size(); i++)
chrom[i] = (uniform() < 0.5) ? false : true;
}
};
//-----------------------------------------------------------------------------
// eoBinBitFlip --> chages a bit
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinBitFlip: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinBitFlip"; }
///
void eoBinBitFlip::operator()(Chrom& chrom) const
{
eoUniform<unsigned> uniform(0, chrom.size());
unsigned pos = uniform();
chrom[pos] = !chrom[pos];
}
};
//-----------------------------------------------------------------------------
// eoBinMutation --> classical mutation
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinMutation: public eoMonOp<Chrom>
{
public:
/// (Default) Constructor.
eoBinMutation(const double& _rate = 0.01): rate(_rate), uniform(0.0, 1.0) {}
/// The class name.
string className() const { return "eoBinMutation"; }
///
void operator()(Chrom& chrom) const
{
for (unsigned i = 0; i < chrom.size(); i++)
if (uniform() < rate)
chrom[i] = !chrom[i];
}
private:
double rate;
mutable eoUniform<float> uniform;
};
//-----------------------------------------------------------------------------
// eoBinInversion --> inverts the bits of the chromosome between an interval
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinInversion: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinInversion"; }
///
void operator()(Chrom& chrom) const
{
eoUniform<unsigned> uniform(0, chrom.size() + 1);
unsigned u1 = uniform(), u2;
do u2 = uniform(); while (u1 == u2);
unsigned r1 = min(u1, u2), r2 = max(u1, u2);
reverse(chrom.begin() + r1, chrom.begin() + r2);
}
};
//-----------------------------------------------------------------------------
// eoBinNext --> next binary value
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinNext: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinNext"; }
///
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
continue;
}
else
{
chrom[i] = 1;
break;
}
}
};
//-----------------------------------------------------------------------------
// eoBinPrev --> previos binary value
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinPrev: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinPrev"; }
///
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
break;
}
else
{
chrom[i] = 1;
continue;
}
}
};
//-----------------------------------------------------------------------------
// eoBinCrossover --> classic crossover
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinCrossover: public eoBinOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinCrossover"; }
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
eoUniform<unsigned> uniform(1, min(chrom1.size(), chrom2.size()));
swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin());
}
};
//-----------------------------------------------------------------------------
// eoBinNxOver --> n-point crossover
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinNxOver: public eoBinOp<Chrom>
{
public:
/// (Defualt) Constructor.
eoBinNxOver(const unsigned& _num_points = 2): num_points(_num_points)
{
if (num_points < 1)
{
cerr << "NxOver --> invalid number of points " << num_points << endl;
exit(EXIT_FAILURE);
}
}
/// The class name.
string className() const { return "eoBinNxOver"; }
///
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_size = min(chrom1.size(), chrom2.size());
unsigned max_points = min(max_size - 1, num_points);
vector<bool> points(max_size, false);
eoUniform<unsigned> uniform(1, max_size);
// select ranges of bits to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
max_points--;
}
} while (max_points);
// swap bits between chromosomes
bool change = false;
for (unsigned bit = 1; bit < points.size(); bit++)
{
if (points[bit])
change = !change;
if (change)
swap(chrom1[bit], chrom2[bit]);
}
}
private:
unsigned num_points;
};
//-----------------------------------------------------------------------------
// eoBinGxOver --> gene crossover
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinGxOver: public eoBinOp<Chrom>
{
public:
/// Constructor.
eoBinGxOver(const unsigned _gene_size, const unsigned _num_points = 2):
gene_size(_gene_size), num_points(_num_points)
{
if (gene_size < 1)
{
cerr << "GxOver --> invalid gene size " << gene_size << endl;
exit(EXIT_FAILURE);
}
if (num_points < 1)
{
cerr << "GxOver --> invalid number of points " << num_points << endl;
exit(EXIT_FAILURE);
}
}
/// The class name
string className() const { return "eoBinGxOver"; }
///
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_genes = min(chrom1.size(), chrom2.size()) / gene_size;
unsigned cut_genes = min(max_genes, num_points);
vector<bool> points(max_genes, false);
eoUniform<unsigned> uniform(0, max_genes);
// selects genes to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
cut_genes--;
}
} while (cut_genes);
// swaps genes
for (unsigned i = 0; i < points.size(); i++)
if (points[i])
swap_ranges(chrom1.begin() + i * gene_size,
chrom1.begin() + i * gene_size + gene_size,
chrom2.begin() + i * gene_size);
}
private:
unsigned gene_size;
unsigned num_points;
};
//-----------------------------------------------------------------------------
// eoBinUxOver --> uniform crossover
//-----------------------------------------------------------------------------
template<class Chrom> class eoBinUxOver: public eoBinOp<Chrom>
{
public:
/// Constructor.
eoBinUxOver(const float _rate): rate(_rate)
{
if (rate < 0 || rate > 1)
{
cerr << "UxOver --> invalid rate " << rate << endl;
exit(EXIT_FAILURE);
}
}
/// The class name.
string className() const { return "eoBinUxOver"; }
///
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned min_size = min(chrom1.size(), chrom2.size());
eoUniform<float> uniform(0, 1);
for (unsigned bit = 0; bit < min_size; bit++)
if (uniform() < rate)
swap(chrom1[bit], chrom2[bit]);
}
public:
float rate;
};
//-----------------------------------------------------------------------------
#endif eoBin_h

45
eo/src/eoDup.h Normal file
View file

@ -0,0 +1,45 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoKill.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EODUP_h
#define _EODUP_h
#include <eoUniform.h>
#include <eoOp.h>
/// Dup or duplicate: duplicates a gene in a chromosome
template <class EOT>
class eoDup: public eoMonOp<EOT> {
public:
///
eoDup( )
: eoMonOp< EOT >( ){};
/// needed virtual dtor
virtual ~eoDup() {};
///
virtual void operator()( EOT& _eo ) const {
eoUniform<unsigned> uniform( 0, _eo.length() );
unsigned pos = uniform();
_eo.insertGene( pos, _eo.gene(pos) );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoDup";};
//@}
};
#endif

108
eo/src/eoESChrom.h Normal file
View file

@ -0,0 +1,108 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoESChrom.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _eoESCHROM_H
#define _eoESCHROM_H
// STL libraries
#include <vector> // For vector<>
#include <stdexcept>
#include <strstream>
#include <iostream> // for ostream
// EO includes
#include <eoVector.h>
/**@name Chromosomes for evolution strategies
Each chromosome in an evolution strategies is composed of a vector of floating point
values plus a vector of sigmas, that are added to them during mutation
*/
//@{
/** Each gene in an Evolution Strategies is composed of a value plus an standard
deviation, sigma, used for mutation*/
struct eoESGene {
double val, sigma;
eoESGene( double _val = 0, double _sigma = 0 ): val( _val ), sigma( _sigma ) {};
};
/// Tricky operator to avoid errors in some VC++ systems, namely VC 5.0 SP3
bool operator < ( eoESGene _e1, eoESGene _e2 ) {
return _e1.val < _e2.val;
}
/// Tricky operator to avoid errors in some VC++ systems
bool operator == ( eoESGene _e1, eoESGene _e2 ) {
return ( _e1.val == _e2.val ) && ( _e1.sigma == _e2.sigma ) ;
}
///
ostream & operator << ( ostream& _s, const eoESGene& _e ) {
_s << _e.val << ", " << _e.sigma << " | ";
return _s;
}
/// Dummy >>
istream & operator >> ( istream& _s, const eoESGene& _e ) {
_s >> _e.val;
_s >> _e.sigma;
return _s;
}
/** Basic chromosome for evolution strategies (ES), as defined by Rechenberg and
Schwefel. Each chromosomes is composed of "genes"; each one of then is an eoESGene
@see eoESGene
*/
template <typename fitT = float >
class eoESChrom: public eoVector<eoESGene, fitT> {
public:
/// Basic ctor
eoESChrom( ):eoVector<eoESGene, fitT>() {};
/** Ctor using a couple of random number generators
@param _size Lineal length of the object
@param _rnd a random number generator, which returns a random value each time it´s called.
@param _rndS another one, for the sigma
*/
eoESChrom( unsigned _size, eoRnd<double>& _rnd, eoRnd<double>& _rndS )
: eoVector<eoESGene, fitT>( _size ){
for ( iterator i = begin(); i != end(); i ++ ) {
i->val = _rnd();
i->sigma = _rndS();
}
};
/// Copy ctor
eoESChrom( const eoESChrom& _eoes): eoVector<eoESGene, fitT>( _eoes ) {};
/// Assignment operator
const eoESChrom& operator =( const eoESChrom & _eoes ) {
if ( this != &_eoes ){
eoVector<eoESGene, fitT>::operator=( _eoes );
}
return *this;
}
///
~eoESChrom() {};
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoESChrom";};
//@}
};
//@}
#endif

34
eo/src/eoEvalFunc.h Normal file
View file

@ -0,0 +1,34 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoEvalFunc.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef eoEvalFunc_H
#define eoEvalFunc_H
/** Evaluate: takes one EO and sets its "fitness" property
* returning this fitness also. That is why EOT is passed by
* non-const reference: it must be altered within evaluate.\\
The requirements on the types with which this class is to be
instantiated with are null, or else, they depend on the particular
class it's going to be applied to; EO does not impose any requirement
on it. If you subclass this abstract class, and use it to evaluate an
EO, the requirements on this EO will depend on the evaluator.
*/
template< class EOT >
struct eoEvalFunc {
#ifdef _MSC_VER
typedef EOT::Fitness EOFitT;
#else
typedef typename Fitness::EOFitT EOFitT;
#endif
/// Effectively applies the evaluation function to an EO or urEO
virtual EOFitT evaluate( EOT & _eo ) const = 0;
};
#endif

53
eo/src/eoEvaluator.h Normal file
View file

@ -0,0 +1,53 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoEvaluator.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOEVALUATOR_H
#define _EOEVALUATOR_H
//-----------------------------------------------------------------------------
#include <eoPopOps.h>
#include <eoEvalFunc.h>
//-----------------------------------------------------------------------------
/** Evaluator takes a vector of EOs and evaluates its fitness
* returning void. Template instances must be of fitness and EO type
*/
template<class EOT>
class eoEvaluator: public eoTransform<EOT>{
public:
/// ctor
eoEvaluator( const eoEvalFunc< EOT> & _ef )
: eoTransform<EOT>(), repEF( _ef ){};
/// Needed virtual destructor
virtual ~eoEvaluator() {};
/* Sets the evaluation function
virtual void EF( const eoEvalFunc< EOT> & _ef ) { repEF= _ef;};*/
/// Gets the evaluation function
virtual const eoEvalFunc< EOT>& EF() { return repEF;};
/** This is the actual function operator(); it is left without implementation.
It takes a vector of pointers to eo
* @param _vEO is a vector of pointers to eo, that will be evaluated
*/
///@name eoObject methods
//@{
/** Return the class id */
virtual string className() const { return "eoEvaluator"; }
/** Read and print are left without implementation */
//@}
private:
const eoEvalFunc< EOT> & repEF;
};
//@}
#endif

55
eo/src/eoFactory.h Normal file
View file

@ -0,0 +1,55 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoFactory.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOFACTORY_H
#define _EOFACTORY_H
//-----------------------------------------------------------------------------
#include <eoObject.h>
//-----------------------------------------------------------------------------
/** EO Factory. A factory is used to create other objects. In particular,
it can be used so that objects of that kind can´t be created in any other
way. It should be instantiated with anything that needs a factory, like selectors
or whatever; but the instance class should be the parent class from which all the
object that are going to be created descend. This class basically defines an interface,
as usual. The base factory class for each hierarchy should be redefined every time a new
object is added to the hierarchy, which is not too good, but in any case, some code would
have to be modified*/
template<class EOClass>
class eoFactory: public eoObject {
public:
/// @name ctors and dtors
//{@
/// constructor
eoFactory( ) {}
/// destructor
virtual ~eoFactory() {}
//@}
/** Another factory methods: creates an object from an istream, reading from
it whatever is needed to create the object. Usually, the format for the istream will be\\
objectType parameter1 parameter2 ... parametern\\
*/
virtual EOClass* make(istream& _is) = 0;
///@name eoObject methods
//@{
/** Return the class id */
virtual string className() const { return "eoFactory"; }
/** Read and print are left without implementation */
//@}
};
#endif _EOFACTORY_H

36
eo/src/eoFitness.h Normal file
View file

@ -0,0 +1,36 @@
//-----------------------------------------------------------------------------
// eoFitness.cpp
// (c) GeNeura Team 1998
//-----------------------------------------------------------------------------
#ifndef EOFITNESS_H
#define EOFITNESS_H
//-----------------------------------------------------------------------------
class eoFitness: public eoPersistent
{
public:
virtual bool operator<(const eoFitness& other) const = 0;
bool operator>(const eoFitness& other) const
{
return !(*this < other || *this == other);
}
bool operator==(const eoFitness& other) const
{
return !(other < *this || *this < other);
}
bool operator!=(const eoFitness& other) const
{
return other < *this || *this < other;
}
virtual operator float() const = 0;
};
//-----------------------------------------------------------------------------
#endif EOFITNESS_H

43
eo/src/eoGA.h Normal file
View file

@ -0,0 +1,43 @@
//-----------------------------------------------------------------------------
// eoGA.h
//-----------------------------------------------------------------------------
#ifndef eoGA_h
#define eoGA_h
//-----------------------------------------------------------------------------
#include <eoPop.h> // eoPop
#include <eoPopOps.h> // eoSelect, eoTranform, eoMerge
//-----------------------------------------------------------------------------
// eoGA
//-----------------------------------------------------------------------------
class eoGA
{
public:
/// Constructor.
eoGA(eoSelect& _select, eoTranform& _transform, eoMerge& _replace)
{
}
///
void operator()(eoPop& pop)
{
eoPop breeders;
select(pop, breeders);
transform(breeders);
replace(breeders, pop);
}
private:
eoSelect& select;
eoTranform& transform;
eoMerge& replace;
};
//-----------------------------------------------------------------------------
#endif eoGA_h

92
eo/src/eoID.h Normal file
View file

@ -0,0 +1,92 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoID.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef EOID_H
#define EOID_H
//-----------------------------------------------------------------------------
#include <iostream> // istream, ostream
#include <string> // for string
using namespace std;
//-----------------------------------------------------------------------------
// eoID
//-----------------------------------------------------------------------------
/** eoID is a template class that adds an ID to an object.\\
Requisites for template instantiation are that the object must admit a default ctor
and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className,
printOn, readFrom, that is why we don´t subclass eoObject to avoid multiple inheritance.\\
IDs can be used to count objects of a a kind, or track them, or whatever.
@see eoObject
*/
template <class Object>
class eoID: public Object
{
public:
/// Main ctor from an already built Object.
eoID( const Object& _o): Object( _o ), thisID(globalID++) {};
/// Copy constructor.
eoID( const eoID& _id): Object( _id ), thisID(globalID++ ) {};
/// Virtual dtor. They are needed in virtual class hierarchies
virtual ~eoID() {};
///returns the age of the object
unsigned long ID() const {return thisID;}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d
*/
//@{
/** Return the class id. This should be redefined in each class; but
it's got code as an example of implementation. Only "leaf" classes
can be non-virtual.
*/
virtual string className() const { return string("[eoID]")+Object::className(); };
/**
* Read object.
* @param _is A istream.
* @throw runtime_exception If a valid object can't be read.
*/
virtual void readFrom(istream& _is) {
Object::readFrom( _is );
_is >> thisID;
}
/**
* Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream.
*/
virtual void printOn(ostream& _os) const{
Object::printOn( _os );
_os << thisID;
}
//@}
private:
/** Default Constructor. \\
It´s private so that it is not used anywhere; the right way of using this object
is to create an Object and passing it to an aged by means of the copy ctor; that way
it´s turned into an Aged object*/
eoID(): Object(), thisID( globalID++ ) {};
unsigned long thisID;
static unsigned long globalID;
};
template< class Object>
unsigned long eoID< Object >::globalID = 0;
#endif EOID_H

44
eo/src/eoKill.h Normal file
View file

@ -0,0 +1,44 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoKill.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOKILL_h
#define _EOKILL_h
#include <eoUniform.h>
#include <eoOp.h>
/// Kill eliminates a gen in a chromosome
template <class EOT >
class eoKill: public eoMonOp<EOT> {
public:
///
eoKill( )
: eoMonOp< EOT >(){};
/// needed virtual dtor
virtual ~eoKill() {};
///
virtual void operator()( EOT& _eo ) const {
eoUniform<unsigned> uniform( 0, _eo.length() );
unsigned pos = uniform( );
_eo.deleteGene( pos );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoKill";};
//@}
};
#endif

60
eo/src/eoLottery.h Normal file
View file

@ -0,0 +1,60 @@
//-----------------------------------------------------------------------------
// eoLottery.h
//-----------------------------------------------------------------------------
#ifndef eoLottery_h
#define eoLottery_h
//-----------------------------------------------------------------------------
#include <eo>
//-----------------------------------------------------------------------------
// eoLottery
//-----------------------------------------------------------------------------
template<class Chrom> class eoLottery: public eoSelect<Chrom>
{
public:
eoLottery(const float& rate = 1.0): eoLottery(rate) {}
void operator()(const eoPop<Chrom>& pop, eoPop<Chrom>& breeders)
{
// scores of chromosomes
vector<float> score(pop.size());
// calculates accumulated scores for chromosomes
transform(pop.begin(), pop.end(), score.begin(), fitness);
float sum = accumulate(score.begin(), score.end(), MINFLOAT);
transform(score.begin(), score.end(), score.begin(),
bind2nd(divides<float>(), sum));
partial_sum(score.begin(), score.end(), score.begin());
// generates random numbers
vector<float> random(pop.size());
generate(random.begin(), random.end(), Uniform<float>(0,1));
sort(random.begin(), random.end(), less<float>());
// selection of chromosomes
unsigned score_index = 0; // position in score vector
unsigned random_index = 0; // position in random vector
unsigned num_chroms = (unsigned)(rate * pop.size());
do {
if(random[random_index] < score[score_index])
{
breeders.push_back(pop[score_index]);
random_index++;
}
else
if (score_index < pop.size())
score_index++;
else
fill_n(back_insert_iterator<Pop>(breeders),
num_chroms - breeders.size(), pop.back());
} while (breeders.size() < num_chroms);
}
};
//-----------------------------------------------------------------------------
#endif eoLottery_h

63
eo/src/eoMerge.h Normal file
View file

@ -0,0 +1,63 @@
//-----------------------------------------------------------------------------
// eoMerge.h
//-----------------------------------------------------------------------------
#ifndef eoMerge_h
#define eoMerge_h
//-----------------------------------------------------------------------------
#include <eoPopOps.h> // eoMerge
//-----------------------------------------------------------------------------
// eoInsertion
//-----------------------------------------------------------------------------
template<class Chrom> class Insertion: public eoMerge<Chrom>
{
public:
eoInsertion(const float& _rate = 1): eoMerge<Chrom>(rate) {}
bool compare(const Chrom& chrom1, const Chrom& chrom2)
{
return chrom1.fitness() < chrom2.fitness();
}
void operator()(const Pop& breeders, Pop& pop)
{
sort(pop.begin(), pop.end() compare);
pop.erase(pop.end() + (int)(pop.size() * (rate - 1) - breeders.size()),
pop.end());
copy(breeders.begin(), breeders.end(),
back_insert_iterator<Pop>(pop));
}
};
//-----------------------------------------------------------------------------
template<class Fitness> class Inclusion: public Replace<Fitness>
{
public:
Inclusion(const float& rate = 1): Replace<Fitness>(rate) {}
void operator()(Pop& breeders, Pop& pop)
{
Pop temp;
sort(breeders.begin(), breeders.end(), compare);
sort(pop.begin(), pop.end(), compare);
merge(breeders.begin(), breeders.end(),
pop.begin(), pop.end(),
back_insert_iterator<Pop>(temp), compare);
temp.erase(temp.begin() + (unsigned)(rate * pop.size()), temp.end());
pop.swap(temp);
}
};
//-----------------------------------------------------------------------------
#endif eoMerge_h

68
eo/src/eoMonOpFactory.h Normal file
View file

@ -0,0 +1,68 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoMonOpFactory.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOMONOPFACTORY_H
#define _EOMONOPFACTORY_H
#include <eoFactory.h>
#include <eoDup.h>
#include <eoKill.h>
#include <eoTranspose.h>
//-----------------------------------------------------------------------------
/** EO Factory. An instance of the factory class to create monary operators.
@see eoSelect*/
template< class EOT>
class eoMonOpFactory: public eoFactory< eoMonOp<EOT> > {
public:
/// @name ctors and dtors
//{@
/// constructor
eoMonOpFactory( ) {}
/// destructor
virtual ~eoMonOpFactory() {}
//@}
/** Another factory method: creates an object from an istream, reading from
it whatever is needed to create the object. Usually, the format for the istream will be\\
objectType parameter1 parameter2 ... parametern\\
*/
virtual eoMonOp<EOT>* make(istream& _is) {
eoMonOp<EOT> * opPtr;
string objectTypeStr;
_is >> objectTypeStr;
if ( objectTypeStr == "eoDup") {
opPtr = new eoDup<EOT>();
}
if ( objectTypeStr == "eoKill" ) {
opPtr = new eoKill<EOT>( );
}
if ( objectTypeStr == "eoTranspose" ) {
opPtr = new eoTranspose<EOT>( );
}
if ( !opPtr ) {
throw runtime_error( "Incorrect selector type" );
}
return opPtr;
}
///@name eoObject methods
//@{
void printOn( ostream& _os ) const {};
void readFrom( istream& _is ){};
/** className is inherited */
//@}
};
#endif _EOFACTORY_H

63
eo/src/eoMultiMonOp.h Normal file
View file

@ -0,0 +1,63 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoMultiMonOp.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOMULTIMONOP_h
#define _EOMULTIMONOP_h
#include <iterator>
#include <eoOp.h>
/** MultiMonOp combines several monary operators. By itself, it does nothing to the
EO it´s handled*/
template <class EOT>
class eoMultiMonOp: public eoMonOp<EOT> {
public:
/// Ctor from an already existing op
eoMultiMonOp( const eoMonOp<EOT>* _op )
: eoMonOp< EOT >( ), vOp(){
vOp.push_back( _op );
};
///
eoMultiMonOp( )
: eoMonOp< EOT >( ), vOp(){};
/// Ctor from an already existing op
void adOp( const eoMonOp<EOT>* _op ){
vOp.push_back( _op );
};
/// needed virtual dtor
virtual ~eoMultiMonOp() {};
///
/// Applies all operators to the EO
virtual void operator()( EOT& _eo ) const {
if ( vOp.begin() != vOp.end() ) {
for ( vector<const eoMonOp<EOT>* >::const_iterator i = vOp.begin();
i != vOp.end(); i++ ) {
(*i)->operator () ( _eo );
}
}
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoMonOp";};
//@}
private:
vector< const eoMonOp<EOT>* > vOp;
};
#endif

116
eo/src/eoMutation.h Normal file
View file

@ -0,0 +1,116 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoMutation.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOMUTATION_H
#define _EOMUTATION_H
#include <math.h>
// EO includes
#include <eoOp.h>
#include <eoUniform.h>
/** Generic Mutation of an EO.
This is a virtual class, just to establish the interface
*/
template <class EOT>
class eoMutation: public eoMonOp<EOT> {
public:
///
eoMutation(const double _rate=0.0) : eoMonOp< EOT >(), rate(_rate) {};
///
virtual ~eoMutation() {};
///
virtual void operator()( EOT& _eo ) const {
for ( unsigned i = 0; i < _eo.length(); i ++ )
applyAt( _eo, i );
}
/// To print me on a stream.
/// @param os The ostream.
void printOn(ostream& os) const {
os << rate ;
}
/// To read me from a stream.
/// @param is The istream.
void readFrom(istream& is) {
is >> rate ;
}
/** @name Methods from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoMutation";};
//@}
protected:
double rate;
private:
#ifdef _MSC_VER
typedef EOT::Type Type;
#else
typedef typename EOT::Type Type;
#endif
/// applies operator to one gene in the EO. It is empty, so each descent class must define it.
virtual void applyAt( EOT& _eo, unsigned _i ) const = 0 ;
};
/** Mutation of an eoString.
The eoString's genes are changed by adding or substracting 1 to
*/
template <class EOT>
class eoStringMutation: public eoMutation<EOT> {
public:
///
eoStringMutation(const double _rate=0.0) : eoMutation< EOT >(_rate) {};
///
virtual ~eoStringMutation() {};
/** @name Methods from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoStringMutation";};
//@}
private:
#ifdef _MSC_VER
typedef EOT::Type Type;
#else
typedef typename EOT::Type Type;
#endif
/// applies operator to one gene in the EO. It increments or decrements the value of that gene by one.
virtual void applyAt( EOT& _eo, unsigned _i ) const {
eoUniform<double> uniform( 0, 1 );
if( rate < uniform() ) {
_eo.gene(_i) += ( uniform()>=0.5 )? (1) : (-1) ;
}
}
};
//-----------------------------------------------------------------------------
#endif

50
eo/src/eoNegExp.h Normal file
View file

@ -0,0 +1,50 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoNegExp.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EONEGEXP_H
#define _EONEGEXP_H
//-----------------------------------------------------------------------------
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <eoRnd.h> // for base class
//-----------------------------------------------------------------------------
// Class eoNegExp
//-----------------------------------------------------------------------------
/// Generates random numbers using a negative exponential distribution
template<class T>
class eoNegExp: public eoRnd<T>
{
public:
/**
* Default constructor.
* @param _mean Dsitribution mean
*/
eoNegExp(T _mean): eoRnd<T>(), mean(_mean) {};
/**
* Copy constructor.
* @param _rnd the copyee
*/
eoNegExp( const eoNegExp& _rnd): eoRnd<T>( _rnd), mean(_rnd.mean) {};
/// Returns an uniform dandom number over the interval [min, max).
virtual T operator()() { return - mean*log((double)rand() / RAND_MAX); }
private:
T mean;
};
//-----------------------------------------------------------------------------
#endif

74
eo/src/eoNormal.h Normal file
View file

@ -0,0 +1,74 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoNormal.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EONORMAL_H
#define _EONORMAL_H
//-----------------------------------------------------------------------------
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <eoRnd.h> // for base class
//-----------------------------------------------------------------------------
// Class eoNormal
//-----------------------------------------------------------------------------
/// Generates random number using a normal distribution
template<class T>
class eoNormal: public eoRnd<T>
{
public:
/**
* Default constructor.
* @param _mean Dsitribution mean
* @param _sd Standard Deviation
*/
eoNormal(T _mean, T _sd)
: eoRnd<T>(), mean(_mean), sd(_sd), phase(false) {}
/**
* Copy constructor.
* @param _rnd the other one
*/
eoNormal( const eoNormal& _rnd )
: eoRnd<T>( _rnd), mean(_rnd.mean), sd(_rnd.sd), phase(false) {}
/** Returns an uniform random number over the interval [min, max).
@return an uniform random number over the interval [min, max).
*/
virtual T operator()() {
if (phase) { // Already have one stored up.
phase = false;
return T ( (sqRatio * q * sd) + mean );
}
double p, v;
do {
p = ((double)rand() / RAND_MAX)*2-1;
q = ((double)rand() / RAND_MAX)*2-1;
v = p*p + q*q;
} while(v > 1.0 || v <0.25);
sqRatio = sqrt(-2*log((double)rand() / RAND_MAX) / v);
phase = true;
return T( (sqRatio * p * sd) + mean );
};
private:
T mean;
T sd;
bool phase;
double sqRatio, q;
};
//-----------------------------------------------------------------------------
#endif

25
eo/src/eoObject.cpp Normal file
View file

@ -0,0 +1,25 @@
//-----------------------------------------------------------------------------
// eoObject.cpp
//-----------------------------------------------------------------------------
#include <eoObject.h>
//-----------------------------------------------------------------------------
// Implementation of these objects
//-----------------------------------------------------------------------------
/*
ostream & operator << ( ostream& _os, const eoObject& _o ) {
_o.printOn(_os);
return _os;
}
//-----------------------------------------------------------------------------
istream & operator >> ( istream& _is, eoObject& _o ) {
_o.readFrom(_is);
return _is;
}
*/
//-----------------------------------------------------------------------------

48
eo/src/eoObject.h Normal file
View file

@ -0,0 +1,48 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoObject.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef EOOBJECT_H
#define EOOBJECT_H
//-----------------------------------------------------------------------------
#include <iostream> // istream, ostream
#include <string> // para string
using namespace std;
//-----------------------------------------------------------------------------
// eoObject
//-----------------------------------------------------------------------------
/**
This is the base class for the whole hierarchy; an eoObject defines
basically an interface for the whole hierarchy: each object should
know its name (#className#). Previously, this object defined a print and read
interface, but it´s been moved to eoPrintable and eoPersistent.
*/
class eoObject
{
public:
/// Default Constructor.
eoObject() {}
/// Copy constructor.
eoObject( const eoObject& ) {}
/// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoObject() {}
/** Return the class id. This should be redefined in each class; but
it's got code as an example of implementation. Only "leaf" classes
can be non-virtual.
*/
virtual string className() const { return "eoObject"; }
};
#endif EOOBJECT_H

182
eo/src/eoOp.h Normal file
View file

@ -0,0 +1,182 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoOp.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _eoOp_H
#define _eoOp_H
#include <vector>
#include <eoObject.h>
#include <eoPrintable.h>
/** @name Genetic operators
What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with
eoOp as father and eoMonOp (monary or unary operator) and eoBinOp (binary operator) as siblings. Nobody
should subclass eoOp, you should subclass eoBinOp or eoMonOp, those are the ones actually used here.
@author GeNeura Team
@version 0.0
*/
//@{
///
enum Arity { unary = 0, binary = 1, Nary = 2};
/** Abstract data types for EO operators.
* Genetic operators act on chromosomes, changing them. The type to instantiate them should
* be an eoObject, but in any case, they are type-specific; each kind of evolvable object
* can have its own operators
*/
template<class EOType>
class eoOp: public eoObject, public eoPrintable {
public:
/// Ctor
eoOp( Arity _arity = unary )
:arity( _arity ) {};
/// Copy Ctor
eoOp( const eoOp& _eop )
:arity( _eop.arity ) {};
/// Needed virtual destructor
virtual ~eoOp(){};
/// Arity: number of operands
Arity readArity() const {return arity;};
/** @name Methods from eoObject */
//@{
/**
* Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream.
*/
virtual void printOn(ostream& _os) const {
_os << className();
_os << arity;
};
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoOp";};
//@}
private:
/// arity is the number of operands it takes
Arity arity;
};
/** Binary genetic operator: subclasses eoOp, and defines
basically the operator() with two operands
*/
template<class EOType>
class eoBinOp: public eoOp<EOType> {
public:
/// Ctor
eoBinOp()
:eoOp<EOType>( binary ) {};
/// Copy Ctor
eoBinOp( const eoBinOp& _ebop )
: eoOp<EOType>( _ebop ){};
/// Dtor
~eoBinOp () {};
/** applies operator, to the object. If arity is more than 1,
* keeps a copy of the operand in a cache.
*/
virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoBinOp";};
//@}
};
/** eoMonOp is the monary operator: genetic operator that takes
only one EO
*/
template <class EOType>
class eoMonOp: public eoOp<EOType> {
public:
/// Ctor
eoMonOp( )
:eoOp<EOType>( unary ) {};
/// Copy Ctor
eoMonOp( const eoMonOp& _emop )
: eoOp<EOType>( _emop ){};
/// Dtor
~eoMonOp() {};
/** applies randomly operator, to the object. If arity is more than 1,
* keeps a copy of the operand in a cache.
*/
virtual void operator()( EOType& _eo1) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoMonOp";};
//@}
};
/** eoNaryOp is the N-ary operator: genetic operator that takes
several EOs. It could be called an {\em orgy} operator
*/
template <class EOType>
class eoNaryOp: public eoOp<EOType> {
public:
/// Ctor
eoNaryOp( )
:eoOp<EOType>( Nary ) {};
/// Copy Ctor
eoNaryOp( const eoNaryOp& _emop )
: eoOp<EOType>( _emop ){};
/// Dtor
~eoNaryOp() {};
/** applies randomly operator, to the object.
*/
// virtual void operator()( EOPop<EOType> & _eop) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject.
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoNaryOp";};
//@}
};
//@}
#endif

68
eo/src/eoOpSelector.h Normal file
View file

@ -0,0 +1,68 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoOpSelector.h
// (c) GeNeura Team 1998
//-----------------------------------------------------------------------------
#ifndef EOOPSELECTOR_H
#define EOOPSELECTOR_H
//-----------------------------------------------------------------------------
#include <stdexcept> // runtime_error
#include <eoObject.h>
#include <eoPrintable.h>
#include <eoOp.h>
//-----------------------------------------------------------------------------
/** An operator selector is an object that contains a set of EO operators, and
and selects one based on whatever criteria. It will be used in the breeder objects.\\
This class is basically a generic interface for operator selection
*/
template<class EOT>
class eoOpSelector: public eoObject, public eoPrintable
{
public:
typedef unsigned ID;
/** add an operator to the operator set
@param _op a genetic operator, that will be applied in some way
@param _arg the operator rate, usually, or any other argument to the operator
@return an ID that will be used to identify the operator
*/
virtual ID addOp( eoOp<EOT>& _op, float _arg ) = 0;
/** Gets a non-const reference to an operator, so that it can be changed,
modified or whatever
@param _id a previously assigned ID
@throw runtime_exception if the ID does not exist*/
virtual eoOp<EOT>& getOp( ID _id ) = 0;
/** Remove an operator from the operator set
@param _id a previously assigned ID
@throw runtime_exception if the ID does not exist
*/
virtual deleteOp( ID _id ) = 0;
/// Returns a genetic operator according to the established criteria
virtual const eoOp<EOT>& Op() = 0;
/// Methods inherited from eoObject
//@{
/** Return the class id.
@return the class name as a string
*/
virtual string className() const { return "eoOpSelector"; };
/**
* Read object and print objects are left for subclasses to define.
*/
//@}
};
//-----------------------------------------------------------------------------
#endif EO_H

10
eo/src/eoPersistent.cpp Normal file
View file

@ -0,0 +1,10 @@
#include <eoPersistent.h>
//Implementation of these objects
//-----------------------------------------------------------------------------
istream & operator >> ( istream& _is, eoPersistent& _o ) {
_o.readFrom(_is);
return _is;
};

53
eo/src/eoPersistent.h Normal file
View file

@ -0,0 +1,53 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoPersistent.h
// (c) GeNeura Team, 1999
//-----------------------------------------------------------------------------
#ifndef EOPERSISTENT_H
#define EOPERSISTENT_H
/// @name variables Some definitions of variables used throughout the program
//@{
/// max length to store stuff read
const unsigned MAXLINELENGTH=1024;
//@}
//-----------------------------------------------------------------------------
#include <iostream> // istream, ostream
#include <string> // para string
//-----------------------------------------------------------------------------
#include <eoPrintable.h>
using namespace std;
//-----------------------------------------------------------------------------
// eoPersistent
//-----------------------------------------------------------------------------
/**
An persistent object that knows how to write (through functions inherited from
#eoPrintable#) and read itself
*/
class eoPersistent: public eoPrintable
{
public:
/// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoPersistent() {}
/**
* Read object.
* @param _is A istream.
* @throw runtime_exception If a valid object can't be read.
*/
virtual void readFrom(istream& _is) = 0;
};
//-----------------------------------------------------------------------------
///Standard input for all objects in the EO hierarchy
istream & operator >> ( istream& _is, eoPersistent& _o );
#endif EOOBJECT_H

130
eo/src/eoPop.h Normal file
View file

@ -0,0 +1,130 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoPop.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOPOP_H
#define _EOPOP_H
#include <vector>
#include <strstream>
using namespace std;
// from file
#include <eoRnd.h>
#include <eoPersistent.h>
/** Subpopulation: it is used to move parts of population
from one algorithm to another and one population to another. It is safer
to declare it as a separate object. I have no idea if a population can be
some other thing that a vector, but if somebody thinks of it, this concrete
implementation will be moved to "generic" and an abstract Population
interface will be provided.
It can be instantiated with anything, provided that it accepts a "size" and a
random generator in the ctor. This happens to all the eo1d chromosomes declared
so far. EOT must also have a copy ctor, since temporaries are created and copied
to the population.
@author Geneura Team
@version 0.0
*/
template<class EOT>
class eoPop: public vector<EOT>, public eoObject, public eoPersistent {
/// Type is the type of each gene in the chromosome
#ifdef _MSC_VER
typedef EOT::Type Type;
#else
typedef typename EOT::Type Type;
#endif
public:
/** Protected ctor. This is intended to avoid creation of void populations, except
from sibling classes
*/
eoPop()
:vector<EOT>() {};
/** Ctor for fixed-size chromosomes, with variable content
@param _popSize total population size
@param _eoSize chromosome size. EOT should accept a fixed-size ctor
@param _geneRdn random number generator for each of the genes
*/
eoPop( unsigned _popSize, unsigned _eoSize, eoRnd<Type> & _geneRnd )
:vector<EOT>() {
for ( unsigned i = 0; i < _popSize; i ++ ){
EOT tmpEOT( _eoSize, _geneRnd);
push_back( tmpEOT );
}
};
/** Ctor for variable-size chromosomes, with variable content
@param _popSize total population size
@param _sizeRnd RNG for the chromosome size. This will be added 1, just in case.
@param _geneRdn random number generator for each of the genes
*/
eoPop( unsigned _popSize, eoRnd<unsigned> & _sizeRnd, eoRnd<Type> & _geneRnd )
:vector<EOT>() {
for ( unsigned i = 0; i < _popSize; i ++ ){
unsigned size = 1 + _sizeRnd();
EOT tmpEOT( size, _geneRnd);
push_back( tmpEOT );
}
};
/** Ctor from an istream; reads the population from a stream,
each element should be in different lines
@param _is the stream
*/
eoPop( istream& _is ):vector<EOT>() {
readFrom( _is );
}
///
~eoPop() {};
/** @name Methods from eoObject */
//@{
/**
* Read object. The EOT class must have a ctor from a stream;
in this case, a strstream is used.
* @param _is A istream.
*/
virtual void readFrom(istream& _is) {
while( _is ) { // reads line by line, and creates an object per
// line
char line[MAXLINELENGTH];
_is.getline( line, MAXLINELENGTH-1 );
if (strlen( line ) ) {
istrstream s( line );
EOT thisEOT( s );
push_back( thisEOT );
}
}
}
/**
* Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream. In this case, prints the population to
standard output. The EOT class must hav standard output with cout,
but since it should be an eoObject anyways, it's no big deal.
*/
virtual void printOn(ostream& _os) const {
copy( begin(), end(), ostream_iterator<EOT>( _os, "\n") );
};
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
string className() const {return "eoPop";};
//@}
protected:
};
#endif

120
eo/src/eoPopOps.h Normal file
View file

@ -0,0 +1,120 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eo1d.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOPOPOPS_H
#define _EOPOPOPS_H
using namespace std;
/**
@author Geneura Team
@version 0.0
*/
//-----------------------------------------------------------------------------
#include <eoPop.h>
//-----------------------------------------------------------------------------
/** eoTransform is a class that transforms or does something on a population.
*/
template<class EOT>
class eoTransform: public eoObject{
public:
/** ctor
*/
eoTransform() {};
/// Dtor
virtual ~eoTransform(){};
/// Pure virtual transformation function. Does something on the population
virtual void operator () ( eoPop<EOT>& _pop ) = 0;
/** @name Methods from eoObject */
//@{
/** readFrom and printOn are not overriden
*/
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
string className() const {return "eoTransform";};
//@}
};
/** eoSelect usually takes elements from one population, with or without
transformation, and transfers them to the other population
*/
template<class EOT>
class eoSelect: public eoObject{
public:
/** ctor
*/
eoSelect() {};
/// Dtor
virtual ~eoSelect(){};
/** Pure virtual transformation function. Extracts something from the parents,
and transfers it to the siblings
@param _parents the initial generation. Will be kept constant
@param _siblings the created offspring. Will be usually an empty population
*/
virtual void operator () ( const eoPop<EOT>& _parents, eoPop<EOT>& _siblings ) const = 0;
/** @name Methods from eoObject */
//@{
/** readFrom and printOn are not overriden
*/
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
string className() const {return "eoSelect";};
//@}
};
/** eoMerge involves three populations, that can be merged and transformed to
give a third
*/
template<class EOT>
class eoMerge: public eoObject{
public:
/// (Default) Constructor.
eoMerge(const float& _rate = 1.0): rep_rate(_rate) {}
/// Dtor
virtual ~eoMerge() {}
/** Pure virtual transformation function. Extracts something from breeders
* and transfers it to the pop
* @param breeders Tranformed individuals.
* @param pop The original population at the begining, the result at the end
*/
virtual operator () ( const eoPop<EOT>& breeders, eoPop<EOT>& pop ) = 0;
/** @name Methods from eoObject */
//@{
/** readFrom and printOn are not overriden
*/
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
string className() const {return "eoMerge";};
//@}
/// Return the rate to be selected from the original population
float rate() const { return rep_rate; }
private:
float rep_rate;
};
#endif

17
eo/src/eoPrintable.cpp Normal file
View file

@ -0,0 +1,17 @@
//-----------------------------------------------------------------------------
// eoPrintable.cpp
//-----------------------------------------------------------------------------
#include <eoPrintable.h>
//-----------------------------------------------------------------------------
//Implementation of these objects
//-----------------------------------------------------------------------------
ostream & operator << ( ostream& _os, const eoPrintable& _o ) {
_o.printOn(_os);
return _os;
};
//-----------------------------------------------------------------------------

45
eo/src/eoPrintable.h Normal file
View file

@ -0,0 +1,45 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoPrintable.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef EOPRINTABLE_H
#define EOPRINTABLE_H
//-----------------------------------------------------------------------------
#include <iostream> // istream, ostream
#include <string> // para string
using namespace std;
//-----------------------------------------------------------------------------
// eoPrintable
//-----------------------------------------------------------------------------
/**
Base class for objects that can print themselves
(#printOn#). Besides, this file defines the standard output for all the objects;
if the objects define printOn there's no need to define #operator <<#.\\
This functionality was separated from eoObject, since it makes no sense to print
some objects (for instance, a #eoFactory# or a random number generator.
*/
class eoPrintable
{
public:
/// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoPrintable() {}
/**
* Write object. It's called printOn since it prints the object on a stream.
* @param _os A ostream.
*/
virtual void printOn(ostream& _os) const = 0;
};
//-----------------------------------------------------------------------------
///Standard output for all objects in the EO hierarchy
ostream & operator << ( ostream& _os, const eoPrintable& _o );
#endif EOPRINTABLE_H

23
eo/src/eoProblem.h Normal file
View file

@ -0,0 +1,23 @@
//-----------------------------------------------------------------------------
// eoProblem.h
// (c) GeNeura Team 1998
//-----------------------------------------------------------------------------
#ifndef EOPROBLEM_H
#define EOPROBLEM_H
//-----------------------------------------------------------------------------
template<class T> class Problem
{
public:
typedef T Chrom;
typedef typename T::Gene Gene;
typedef typename T::Fitness Fitness;
virtual Fitness operator()(const Chrom& chrom) = 0;
};
//-----------------------------------------------------------------------------
#endif EOPROBLEM_H

View file

@ -0,0 +1,132 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoProportionalOpSel.h
// (c) GeNeura Team 1998
//-----------------------------------------------------------------------------
#ifndef EOPROPORTIONALOPSEL_H
#define EOPROPORTIONALOPSEL_H
//-----------------------------------------------------------------------------
#include <stdexcept> // runtime_error
#include <functional> // greater
#include <map>
// Includes from EO
#include <eoUniform.h>
#include <eoOpSelector.h>
#include <eoOp.h>
//-----------------------------------------------------------------------------
/** This class selects operators according to probability. All operator percentages
should add up to one; if not, an exception will be raised.\\
Operators are represented as pairs (proportion,operator)
*/
template<class EOT>
class eoProportionalOpSel: public eoOpSelector<EOT>,
public multimap<float,eoOp<EOT>*,greater<float> >
{
public:
typedef multimap<float,eoOp<EOT>*,greater<float> > MMF;
/// default ctor
eoProportionalOpSel()
: eoOpSelector<EOT>(), MMF(), opID(1) {};
/// virtual dtor
virtual ~eoProportionalOpSel() {};
/** Gets a non-const reference to an operator, so that it can be changed,
modified or whatever
@param _id a previously assigned ID
@throw runtime_error if the ID does not exist*/
virtual eoOp<EOT>& getOp( ID _id ) {
MMF::iterator i=begin();
ID j = 1;
while ( (i++!=end()) && (j++ != _id) );
if ( i == end() )
throw runtime_error( "No such id in eoProportionalOpSel::op\n" );
return *(i->second);
}
/** add an operator to the operator set
@param _op a genetic operator, that will be applied in some way
@param _arg an argument to the operator, usually operator rate
@return an ID that will be used to identify the operator
*/
virtual ID addOp( eoOp<EOT>& _op, float _arg ) {
insert( MMF::value_type( _arg,& _op ) );
return opID++;
}
/** Remove an operator from the operator set
@param _id a previously assigned ID
@throw runtime_error if the ID does not exist
*/
virtual deleteOp( ID _id ) {
unsigned j;
MMF::iterator i;
for ( i=begin(), j=1; i!=end(); i++,j++ ) {
if( j == _id )
erase( i );
}
if ( i == end() )
throw runtime_error( "No such id in eoProportionalOpSel::op\n" );
};
/// Returns a genetic operator according to the established criteria
virtual const eoOp<EOT>& Op() {
// Check that all add up to one
float acc = 0;
MMF::iterator i;
unsigned j;
for ( i=begin(), j=1; i!=end(); i++,j++ ) {
acc +=i->first;
}
if ( acc != 1.0 )
throw runtime_error( "Operator rates added up different from 1.0" );
// If here, operators ordered by rate and no problem
eoUniform<float> u(0,1.0);
float aRnd = u();
i=begin();
acc = 0;
do {
acc += i->first;
} while ( (acc <= aRnd ) && (i++!=end() ) );
if ( i == end() )
throw runtime_error( "Operator not found in eoProportionalOpSelector" );
return *(i->second);
}
/// Methods inherited from eoObject
//@{
/** Return the class id.
@return the class name as a string
*/
virtual string className() const { return "eoProportionalOpSel"; };
/** Print itself: inherited from eoObject implementation. Declared virtual so that
it can be reimplemented anywhere. Instance from base classes are processed in
base classes, so you don´t have to worry about, for instance, fitness.
@param _s the ostream in which things are written*/
virtual void printOn( ostream& _s ) const{
for ( MMF::const_iterator i=begin(); i!=end(); i++ ) {
_s << i->first << "\t" << i->second << endl;
}
}
//@}
private:
ID opID;
};
//-----------------------------------------------------------------------------
#endif EO_H

183
eo/src/eoRandomBreed.h Normal file
View file

@ -0,0 +1,183 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRandomBreed.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EORANDOMBREED_H
#define _EORANDOMBREED_H
#include <eoSelector.h>
/** Takes those on the selection list and creates a list of new individuals
* Destroys the genetic pool */
template<class EOT>
class EORandomBreed: public EOBreeder<EOT>{
public:
typedef vector< EOOp<EOT > * > vecOpT;
/// Ctor
EORandomBreed():vecOp() {};
/** Copy ctor
* Needs a copy ctor for the EO operators */
EORandomBreed( const EORandomBreed& _rndBreeder)
:vecOp() {
copy( _rndBreeder.vecOp.begin(), _rndBreeder.vecOp.end(),
vecOp.begin() );
};
/// Dtor
virtual ~EORandomBreed() {};
/// Adds a genetic operator to the Breeder with a rate
virtual void addOp( EOOp<EOT>* _eop ) {
vecOp.push_back( _eop);
};
/// Takes the operator pointed to from the operator list
virtual void deleteOp( const EOOp<EOT>* _eop);
/** Takes the genetic pool, and returns next generation, destroying the
* genetic pool container
* Non-const because it might order the operator vector. In this case,
* it mates all members of the population randomly */
virtual void operator() ( EOPop< EOT >& _ptVeo );
// I don´t like this, but I need it for the RandomBreedLog
protected:
vecOpT vecOp;
};
//_________________________ IMPLEMENTATIONS _____________________________
template< class EOT>
void EORandomBreed<EOT>::deleteOp( const EOOp<EOT>* _eop) {
vecOpT::iterator i;
for ( i = vecOp.begin(); i != vecOp.end(); i++ ) {
if ( *i == _eop ) {
vecOp.erase( i );
}
}
}
//________________________________________________________________________
template<class EOT>
void EORandomBreed<EOT>::operator() ( EOPop< EOT >& _ptVeo ) {
unsigned select= _ptVeo.size(); // New population same size than old
sort( vecOp.begin(), vecOp.end(), SortEOpPt<EOT>() );
unsigned i;
float totalPriority = 0;
for ( i = 0; i < vecOp.size(); i ++ ) {
totalPriority += vecOp[i]->Priority();
}
unsigned inLen = _ptVeo.size(); // size of in subPop
for ( i = 0; i < select; i ++ ) {
// Create an alias of a random input EO with copy ctor
EOT& newEO = _ptVeo[ i ];
// Choose operator
float randomDraw = totalPriority *(rand() % 1000) /1000.0;
vecOpT::const_iterator j;
float accumulated = 0;
for ( j = vecOp.begin();
( j != vecOp.end() ) && ( accumulated < randomDraw);
j ++ ) {
accumulated+= (*j)->Priority(); // the priority
}
if ( j != vecOp.begin() )
j--; // previous one
EOOp<EOT >* thisOp = *j;
if (thisOp->readArity() == unary ) {
MonOp<EOT>* mopPt = dynamic_cast< MonOp<EOT>* > ( thisOp );
(*mopPt)( newEO );
} else {
unsigned chosenMatch = rand() % inLen;
BinOp<EOT>* bopPt = dynamic_cast< BinOp<EOT>* > ( thisOp );
(*bopPt)( newEO, _ptVeo[chosenMatch] );
}
}
}
#include <ADT/EOFactory.h> // For factory
/** Exactly as RandomBreed, except that uses factories*/
template<class EOT>
class EORandomBreedLog: public EORandomBreed<EOT>{
public:
typedef vector< EOOp<EOT > * > vecOpT;
/// Ctor
EORandomBreedLog( EOFactory<EOT> & _eof ):EORandomBreed<EOT>(), factory( _eof ) {};
/** Copy ctor
* Needs a copy ctor for the EO operators */
EORandomBreedLog( const EORandomBreedLog& _rndBreeder)
:EORandomBreed<EOT>( _rndBreeder ), factory( _rndBreeder.factory) {};
/// Dtor
virtual ~EORandomBreedLog() {};
/** Takes the genetic pool, and returns next generation, destroying the
* genetic pool container
* Non-const because it might order the operator vector. In this case, it mates
* all population randomly */
virtual void operator() ( EOPop< EOT >& _ptVeo ) {
unsigned select= _ptVeo.size(); // New population same size than old
sort( vecOp.begin(), vecOp.end(), SortEOpPt<EOT>() );
unsigned i;
float totalPriority = 0;
for ( i = 0; i < vecOp.size(); i ++ ) {
totalPriority += vecOp[i]->Priority();
}
unsigned inLen = _ptVeo.size(); // size of in subPop
for ( i = 0; i < select; i ++ ) {
// Create a copy of a random input EO with copy ctor
EOT* newEO = factory.make( _ptVeo[ i ] );
// Choose operator
float randomDraw = totalPriority *(rand() % 1000) /1000.0;
vecOpT::const_iterator j;
float accumulated = 0;
for ( j = vecOp.begin();
( j != vecOp.end() ) && ( accumulated < randomDraw);
j ++ ) {
accumulated+= (*j)->Priority(); // the priority
}
if ( j != vecOp.begin() )
j--; // previous one
EOOp<EOT >* thisOp = *j;
if (thisOp->readArity() == unary ) {
MonOp<EOT>* mopPt = dynamic_cast< MonOp<EOT>* > ( thisOp );
(*mopPt)( *newEO );
} else {
unsigned chosenMatch = rand() % inLen;
BinOp<EOT>* bopPt = dynamic_cast< BinOp<EOT>* > ( thisOp );
(*bopPt)( *newEO, _ptVeo[chosenMatch] );
}
}
};
private:
EOFactory<EOT>& factory;
};
#endif

80
eo/src/eoRandomSelect.h Normal file
View file

@ -0,0 +1,80 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRandomSelect.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef EORANDOMSELECT_H
#define EORANDOMSELECT_H
//-----------------------------------------------------------------------------
#include <algorithm>
#include <numeric> // for accumulate
#include <functional>
#include <eoPopOps.h>
#include <eoUniform.h>
//-----------------------------------------------------------------------------
/**
* eoRandomSelect: an selection operator, which selects randomly a percentage
of the initial population.
*/
template<class EOT> class eoRandomSelect: public eoSelect<EOT>
{
public:
///
eoRandomSelect(const float& _percent = 0.4): eoSelect<EOT>(), rate(_percent) {};
///
virtual ~eoRandomSelect() {};
/// Takes a percentage of the population randomly, and transfers it to siblings
virtual void operator() ( const eoPop<EOT>& _parents, eoPop<EOT>& _siblings ) const {
// generates random numbers
eoUniform<unsigned> uniform(0, _parents.size()-1);
unsigned num_chroms = (unsigned)(rate * _parents.size());
// selection of chromosomes
do {
_siblings.push_back(_parents[uniform()]);
} while (_siblings.size() < num_chroms);
}
/// @name Methods from eoObject
//@{
/**
* Read object. Reads the percentage
* Should call base class, just in case.
* @param _s A istream.
*/
virtual void readFrom(istream& _s) {
_s >> rate;
}
/** Print itself: inherited from eoObject implementation. Declared virtual so that
it can be reimplemented anywhere. Instance from base classes are processed in
base classes, so you don´t have to worry about, for instance, fitness.
@param _s the ostream in which things are written*/
virtual void printOn( ostream& _s ) const{
_s << rate;
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoRandomSelect";};
//@}
private:
float rate;
};
//-----------------------------------------------------------------------------
#endif EOGSRANDOMSELECT_H

105
eo/src/eoRank.h Normal file
View file

@ -0,0 +1,105 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRank.h
// (c) GeNeura Team 1999
//-----------------------------------------------------------------------------
#ifndef _eoRank_H
#define _eoRank_H
#include <eoOpSelector.h>
#include <eoPopOps.h>
/**
* Takes those on the selection list and creates a list of new individuals
* Destroys the genetic pool. There's no requisite on EOT, other than the
* genetic operators can be instantiated with it, so it fully depends on
* the genetic operators used. If generic genetic operators are used, then
* EOT must be an EO
*/
template<class EOT>
class eoRank: public eoSelect<EOT>{
public:
/// Ctor
eoRank( unsigned _newPopSize, eoOpSelector<EOT>& _opSelector)
:eoSelect<EOT>(), opSelector( _opSelector ), repNewPopSize( _newPopSize ) {};
/** Copy ctor
* Needs a copy ctor for the EO operators */
eoRank( const eoRank& _rankBreeder)
:eoSelect<EOT>( _rankBreeder),
opSelector( _rankBreeder.opSelector ), repNewPopSize( _rankBreeder.repNewPopSize ) {};
/// Dtor
virtual ~eoRank() {};
/** Takes the genetic pool, and returns next generation, destroying the
* genetic pool container
* Non-const because it might order the operator vector*/
virtual void operator() ( const eoPop< EOT >& _ptVeo,
eoPop< EOT >& _siblings ) const {
unsigned inLen = _ptVeo.size(); // size of subPop
if ( !inLen )
throw runtime_error( "zero population in eoRank");
for ( unsigned i = 0; i < repNewPopSize; i ++ ) {
// Create a copy of a random input EO with copy ctor. The members of the
// population will be selected by rank, with a certain probability of
// being selected several times if the new population is bigger than the
// old
EOT newEO = _ptVeo[ i%inLen ];
// Choose operator
eoUniform<unsigned> u( 0, inLen );
const eoOp<EOT >& thisOp = opSelector.Op();
if ( thisOp.readArity() == unary ) {
const eoMonOp<EOT>& mopPt = dynamic_cast< const eoMonOp<EOT>& > ( thisOp );
mopPt( newEO );
} else {
const eoBinOp<EOT>& bopPt = dynamic_cast< const eoBinOp<EOT>& > ( thisOp );
EOT mate = _ptVeo[ u() ];
bopPt( newEO, mate );
}
_siblings.push_back( newEO );
}
};
/** This is a _new_ function, non defined in the parent class
* It´s used to set the selection rate */
void select( unsigned _select ) {
repNewPopSize = _select;
}
/// Methods inherited from eoObject
//@{
/** Return the class id.
@return the class name as a string
*/
virtual string className() const { return "eoRank"; };
/** Print itself: inherited from eoObject implementation. Declared virtual so that
it can be reimplemented anywhere. Instance from base classes are processed in
base classes, so you don´t have to worry about, for instance, fitness.
@param _s the ostream in which things are written*/
virtual void printOn( ostream& _s ) const{
_s << opSelector;
_s << repNewPopSize;
};
//@}
private:
eoOpSelector<EOT> & opSelector;
unsigned repNewPopSize;
};
#endif

97
eo/src/eoRnd.h Normal file
View file

@ -0,0 +1,97 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRnd.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EORND_H
#define _EORND_H
//-----------------------------------------------------------------------------
#include <eoObject.h>
//-----------------------------------------------------------------------------
// Class eoRnd
//-----------------------------------------------------------------------------
#include <stdlib.h> // srand
#include <time.h> // time
#include <stdexcept> // runtime_error
//-----------------------------------------------------------------------------
#include <eoPersistent.h>
//-----------------------------------------------------------------------------
/**
* Base class for a family of random number generators. Generates numbers
* according to the parameters given in the constructor. Uses the machine's
* own random number generators. Which is not too good, after all.
*/
template<class T>
class eoRnd: public eoObject, public eoPersistent
{
public:
/// default constructor
eoRnd(unsigned _seed = 0) {
if ( !started ) {
srand(_seed?_seed:time(0));
started = true;
}
}
/// Copy cotor
eoRnd(const eoRnd& _r ) {srand(time(0));};
/** Main function: random generators act as functors, that return random numbers.
It´s non-const because it might modify a seed
@return return a random number
*/
virtual T operator()() = 0;
/** Return the class id.
@return the class name as a string
*/
virtual string className() const { return "eoRandom"; };
/**
* Read object.
* @param is A istream.
* @throw runtime_exception If a valid object can't be read.
*/
virtual void readFrom(istream& _is);
/**
* print object. Prints just the ID, since the seed is not accesible.
* @param is A ostream.
*/
void printOn(ostream& _os) const { _os << endl; };
private:
/// true if the RNG has been started already. If it starts every time, means trouble.
static bool started;
};
template<class T> bool eoRnd<T>::started = false;
//--------------------------------------------------------------------------
/**
* Read object.
* @param is A istream.
* @throw runtime_exception If a valid object can't be read.
*/
template<class T>
void eoRnd<T>::readFrom(istream& _is) {
if (!_is)
throw runtime_error("Problems reading from stream in eoRnd");
long seed;
_is >> seed;
srand(seed);
}
#endif

71
eo/src/eoSelectFactory.h Normal file
View file

@ -0,0 +1,71 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// EOFactory.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOSELECTFACTORY_H
#define _EOSELECTFACTORY_H
#include <eoFactory.h>
#include <eoRandomSelect.h>
#include <eoTournament.h>
//-----------------------------------------------------------------------------
/** EO Factory.An instance of the factory class to create selectors, that is,
eoSelect objects
@see eoSelect*/
template< class EOT>
class eoSelectFactory: public eoFactory<eoSelect< EOT> > {
public:
/// @name ctors and dtors
//{@
/// constructor
eoSelectFactory( ) {}
/// destructor
virtual ~eoSelectFactory() {}
//@}
/** Another factory methods: creates an object from an istream, reading from
it whatever is needed to create the object. Usually, the format for the istream will be\\
objectType parameter1 parameter2 ... parametern\\
*/
virtual eoSelect<EOT>* make(istream& _is) {
eoSelect<EOT> * selectPtr;
string objectTypeStr;
_is >> objectTypeStr;
// All selectors have a rate, the proportion of the original population
float rate;
_is >> rate;
if ( objectTypeStr == "eoTournament") {
// another parameter is necessary
unsigned tSize;
_is >> tSize;
selectPtr = new eoTournament<EOT>( rate, tSize );
} else {
if ( objectTypeStr == "eoRandomSelect" ) {
selectPtr = new eoRandomSelect<EOT>( rate );
} else {
throw runtime_error( "Incorrect selector type" );
}
}
return selectPtr;
}
///@name eoObject methods
//@{
void printOn( ostream& _os ) const {};
void readFrom( istream& _is ){};
/** className is inherited */
//@}
};
#endif _EOFACTORY_H

59
eo/src/eoSimpleEval.h Normal file
View file

@ -0,0 +1,59 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoSimpleEval.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOSimpleEval_H
#define _EOSimpleEval_H
#include <eoEvaluator.h> // for evalFunc
#include <algorithm> // For sort
/** Particular instantiation of the EOEvaluator class
It takes each member in the population, and evaluates it, applying
the evaluation function it´s been initialized with
*/
template<class EOT>
class eoSimpleEval: public eoEvaluator<EOT> {
public:
/// Ctors/dtors
eoSimpleEval( eoEvalFunc<EOT> & _ef ):eoEvaluator<EOT>(_ef) {};
///
virtual ~eoSimpleEval() {};
#ifdef _MSC_VER
typedef EOT::Fitness EOFitT;
#else
typedef typename EOT::Fitness EOFitT;
#endif
/** Applies evaluation function to all members in the population, and sets
their fitnesses
Reference is non-const since it orders the population by any order
it´s been defined
@param _vEO the population whose fitness is going to be computed*/
virtual void operator() ( eoPop< EOT >& _vEO ) {
for ( eoPop<EOT>::iterator i = _vEO.begin(); i != _vEO.end(); i ++ ){
i->fitness( EF().evaluate( *i ) );
}
sort( _vEO.begin(), _vEO.end() );
};
///@name eoObject methods
//@{
///
void printOn( ostream& _os ) const {};
///
void readFrom( istream& _is ){};
///
string className() { return "eoSimpleEval";};
//@}
};
#endif

122
eo/src/eoString.h Normal file
View file

@ -0,0 +1,122 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoString.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _eoString_H
#define _eoString_H
// STL libraries
#include <string>
#include <stdexcept>
using namespace std;
// EO headers
#include <eo1d.h>
//-----------------------------------------------------------------------------
// eoString
//-----------------------------------------------------------------------------
/** Adaptor that turns an STL string into an EO */
template <class fitnessT >
class eoString: public eo1d<char, fitnessT>, public string {
public:
/// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator
//@{
/// ctor
eoString( const string& _str ="" )
: eo1d<char, fitnessT>(), string( _str ) {};
/** Ctor using a random number generator
@param _size Lineal length of the object
@param _rnd a random number generator, which returns a random value each time it´s called
*/
eoString( unsigned _size, eoRnd<char>& _rnd )
: eo1d<char, fitnessT>(), string(){
for ( unsigned i = 0; i < _size; i ++ ) {
*this += _rnd();
}
};
/// copy ctor
eoString( const eoString<fitnessT>& _eoStr )
:eo1d<char, fitnessT>( static_cast<const eo1d<char, fitnessT> & > ( _eoStr ) ),
string( _eoStr ){};
/// Assignment operator
const eoString& operator =( const eoString& _eoStr ) {
if ( this != & _eoStr ) {
eo1d<char, fitnessT>::operator = ( _eoStr );
string::operator = ( _eoStr );
}
return *this;
}
/// dtor
virtual ~eoString() {};
//@}
/** methods that implement the eo1d <em>protocol</em>
@exception out_of_range if _i is larger than EO´s size
*/
virtual char gene( unsigned _i ) const {
if ( _i >= length() )
throw out_of_range( "out_of_range when reading gene");
return (*this)[_i];
};
/** methods that implement the eo1d <em>protocol</em>
@exception out_of_range if _i is larger than EO´s size
*/
virtual char& gene( unsigned _i ) {
if ( _i >= size() )
throw out_of_range( "out_of_range when writing a gene");
return (*this)[_i];
};
/** Inserts a value after _i, displacing anything to the right
@exception out_of_range if _i is larger than EO´s size
*/
virtual void insertGene( unsigned _i, char _val ) {
if (_i <= this->size() ) {
string::iterator i = this->begin()+_i;
this->insert( i, _val );
} else
throw out_of_range( "out_of_range when inserting gene");
};
/** Eliminates the gene at position _i
@exception out_of_range if _i is larger than EO´s size
*/
virtual void deleteGene( unsigned _i ) {
if (_i < this->size() ) {
string::iterator i = this->begin()+_i;
this->erase( i );
} else
throw out_of_range( "out_of_range when deleting gene");
};
/// methods that implement the EO <em>protocol</em>
virtual unsigned length() const { return this->size(); };
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoString";};
//@}
};
#endif

93
eo/src/eoTournament.h Normal file
View file

@ -0,0 +1,93 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoTournament.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOGSTOURN_H
#define _EOGSTOURN_H
//-----------------------------------------------------------------------------
#include <eoUniform.h> // for ceil
#include <eoPopOps.h>
//-----------------------------------------------------------------------------
/** Selects those who are going to reproduce using Tournament selection:
a subset of the population of size tournamentSize is chosen,
and the best is selected for the new population .
@author JJ Merelo, 1998
*/
template<class EOT>
class eoTournament:public eoSelect<EOT>{
public:
/// Proportion of guys that are going to be eliminated
eoTournament( float _perc, unsigned _tSize): eoSelect<EOT>(),
perc( _perc), repTournamentSize(_tSize){};
/// Virtual dtor
~eoTournament(){};
/// Set tourn size
void tournamentSize( unsigned _size ) { repTournamentSize = _size; };
/**
* Selects from the initial pop using tournament selection, and copies it
* to the other population.
*/
virtual void operator() ( const eoPop<EOT>& _vEO, eoPop<EOT>& _aVEO) const {
unsigned thisSize = _vEO.size();
// Build vector
for ( unsigned j = 0; j < thisSize*perc; j ++ ) {
// Randomly select a tournamentSize set, and choose the best
eoPop<EOT> veoTournament;
eoUniform<unsigned> u( 0, thisSize);
for ( unsigned k = 0; k < repTournamentSize; k++ ) {
unsigned chosen = u();
EOT newEO = _vEO[chosen];
veoTournament.push_back( newEO );
}
sort( veoTournament.begin(), veoTournament.end() );
// The first is chosen for the new population
_aVEO.push_back( veoTournament.front() );
}
};
/// @name Methods from eoObject
//@{
/**
* Read object. Reads the percentage
* Should call base class, just in case.
* @param _s A istream.
*/
virtual void readFrom(istream& _s) {
_s >> perc >> repTournamentSize;
}
/** Print itself: inherited from eoObject implementation. Declared virtual so that
it can be reimplemented anywhere. Instance from base classes are processed in
base classes, so you don´t have to worry about, for instance, fitness.
@param _s the ostream in which things are written*/
virtual void printOn( ostream& _s ) const{
_s << perc << endl << repTournamentSize << endl;
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoTournament";};
//@}
private:
float perc;
unsigned repTournamentSize;
};
#endif

74
eo/src/eoTranspose.h Normal file
View file

@ -0,0 +1,74 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoTranspose.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOTRANSPOSE_h
#define _EOTRANSPOSE_h
#include <eoUniform.h>
#include <eoOp.h>
/** Transposition operator: interchanges the position of two genes
of an EO. These positions must be defined by an only index, that is,
EOT must subclass eo1d
*/
template <class EOT >
class eoTranspose: public eoMonOp<EOT> {
public:
///
eoTranspose()
: eoMonOp< EOT >( ){};
/// needed virtual dtor
virtual ~eoTranspose() {};
///
virtual void operator()( EOT& _eo ) const {
eoUniform<unsigned> uniform(0, _eo.length() );
unsigned pos1 = uniform(),
pos2 = uniform();
applyAt( _eo, pos1, pos2 );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoTranspose";};
//@}
private:
#ifdef _MSC_VER
typedef EOT::Type Type;
#else
typedef typename EOT::Type Type;
#endif
/** applies operator to one gene in the EO
@param _eo victim of transposition
@param i, j positions of the genes that are going to be changed
@throw runtime_exception if the positions to write are incorrect
*/
virtual void applyAt( EOT& _eo, unsigned _i, unsigned _j) const {
try {
Type tmp = _eo.gene( _i );
_eo.gene( _i ) = _eo.gene( _j );
_eo.gene( _j ) = tmp;
} catch ( exception& _e ) {
string msg = _e.what();
msg += "Caught exception at eoTranspose";
throw runtime_error( msg.c_str() );
}
}
};
#endif

53
eo/src/eoUniform.h Normal file
View file

@ -0,0 +1,53 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// EOUniform.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOUNIFORM_H
#define _EOUNIFORM_H
//-----------------------------------------------------------------------------
#include <time.h>
#include <stdlib.h>
#include <eoRnd.h>
//-----------------------------------------------------------------------------
// Class eoUniform
//-----------------------------------------------------------------------------
/// Generates uniform random number over the interval [min, max)
template<class T>
class eoUniform: public eoRnd<T>
{
public:
/**
* Default constructor.
* @param _min The minimum value in the interval.
* @param _max The maximum value in the interval.
*/
eoUniform(T _min = 0, T _max = 1)
: eoRnd<T>(), minim(_min), diff(_max - _min) {}
/**
* copy constructor.
* @param _rnd the other rnd
*/
eoUniform( const eoUniform& _rnd)
: eoRnd<T>( _rnd), minim(_rnd.minim), diff(_rnd.diff) {}
/// Returns an uniform dandom number over the interval [min, max).
virtual T operator()() {
return minim+ T( (diff * rand() )/ RAND_MAX);
}
private:
T minim;
double diff;
};
//-----------------------------------------------------------------------------
#endif

150
eo/src/eoVector.h Normal file
View file

@ -0,0 +1,150 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoVector.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _eoVector_H
#define _eoVector_H
// STL libraries
#include <vector> // For vector<int>
#include <stdexcept>
#include <strstream>
#include <eo1d.h>
#include <eoRnd.h>
/** Adaptor that turns an STL vector into an EO
with the same gene type as the type with which
the vector has been instantiated
*/
template <class T, class fitnessT>
class eoVector: public eo1d<T, fitnessT>, public vector<T> {
public:
/// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator
//@{
/** Ctor.
@param _size Lineal length of the object
@param _val Common initial value
*/
eoVector( unsigned _size, T _val = 0)
: eo1d<T, fitnessT>(), vector<T>( _size, _val ){ };
/** Ctor using a random number generator
@param _size Lineal length of the object
@param _rnd a random number generator, which returns a random value each time it´s called
*/
eoVector( unsigned _size, eoRnd<T>& _rnd );
/** Ctor from a istream. The T class should accept reading from a istream. It doesn't read fitness,
which is supposed to be dynamic and dependent on environment.
@param _is the input stream; should have all values in a single line, separated by whitespace
*/
eoVector( istream& _is);
/// copy ctor
eoVector( const eoVector & _eo )
: eo1d<T, fitnessT>( _eo ), vector<T>( _eo ){ };
/// Assignment operator
const eoVector& operator =( const eoVector & _eo ) {
if ( this != &_eo ){
eo1d<T, fitnessT>::operator=( _eo );
vector<T>::operator=( _eo );
}
return *this;
}
/// dtor
virtual ~eoVector() {};
//@}
/** methods that implement the eo1d <em>protocol</em>
@exception out_of_range if _i is larger than EO´s size
*/
virtual T gene( unsigned _i ) const {
if ( _i >= length() )
throw out_of_range( "out_of_range when reading gene");
return (*this)[_i];
};
/** methods that implement the eo1d <em>protocol</em>
@exception out_of_range if _i is larger than EO´s size
*/
virtual T& gene( unsigned _i ) {
if ( _i >= size() )
throw out_of_range( "out_of_range when writing a gene");
return (*this)[_i];
};
/** methods that implement the eo1d <em>protocol</em>
@exception out_of_range if _i is larger than EO´s size
*/
virtual void insertGene( unsigned _i, T _val ) {
if (_i <= size() ) {
vector<T>::iterator i = begin()+_i;
insert( i, _val );
} else {
throw out_of_range( "out_of_range when inserting a gene");
}
};
/** Eliminates the gene at position _i
@exception out_of_range if _i is larger than EO´s size
*/
virtual void deleteGene( unsigned _i ) {
if (_i < this->size() ) {
vector<T>::iterator i = this->begin()+_i;
this->erase( i );
} else {
throw out_of_range( "out_of_range when deleting a gene");
};
};
/// methods that implement the EO <em>protocol</em>
virtual unsigned length() const { return this->size(); };
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoVector";};
//@}
};
//____________________________ Some method implementation _______________________
// Ctors______________________________________________________________________________
//____________________________________________________________________________________
template <class T, class fitnessT>
eoVector<T,fitnessT>::eoVector( unsigned _size, eoRnd<T>& _rnd )
: eo1d<T, fitnessT>(), vector<T>( _size ){
for ( iterator i = begin(); i != end(); i ++ ) {
*i = _rnd();
}
};
//____________________________________________________________________________________
template <class T, class fitnessT>
eoVector<T,fitnessT>::eoVector( istream& _is)
: eo1d<T, fitnessT>(), vector<T>( ){
while (_is ) {
T tmp;
_is >> tmp;
push_back( tmp );
}
};
#endif

89
eo/src/eoXOver2.h Normal file
View file

@ -0,0 +1,89 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoXOver2.h
// (c) GeNeura Team, 1998
//-----------------------------------------------------------------------------
#ifndef _EOXOVER2_h
#define _EOXOVER2_h
// for swap
#if defined( __BORLANDC__ )
#include <algorith>
#else
#include <algorithm>
#endif
// EO includes
#include <eoOp.h>
#include <eoUniform.h>
/** 2-point crossover: takes the genes in the central section of two EOs
and interchanges it
*/
template <class EOT>
class eoXOver2: public eoBinOp<EOT> {
public:
///
eoXOver2()
: eoBinOp< EOT >(){};
///
virtual ~eoXOver2() {};
///
virtual void operator()( EOT& _eo1,
EOT& _eo2 ) const {
unsigned len1 = _eo1.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1;
eoUniform<unsigned> uniform( 0, len );
unsigned pos1 = uniform(), pos2 = uniform() ;
applyAt( _eo1, _eo2, pos1, pos2 );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoXOver2";};
//@}
private:
#ifdef _MSC_VER
typedef EOT::Type Type;
#else
typedef typename EOT::Type Type;
#endif
/// applies operator to one gene in the EO
virtual void applyAt( EOT& _eo, EOT& _eo2,
unsigned _i, unsigned _j = 0) const {
if ( _j < _i )
swap( _i, _j );
unsigned len1 = _eo.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1;
if ( (_j > len) || (_i> len ) )
throw runtime_error( "xOver2: applying xOver past boundaries");
for ( unsigned i = _i; i < _j; i++ ) {
Type tmp = _eo.gene( i );
_eo.gene( i ) = _eo2.gene( i );
_eo2.gene( i ) = tmp ;
}
}
};
#endif