Extreme cleanup, see src/obsolete for details

This commit is contained in:
mac 2000-08-10 14:18:34 +00:00
commit 6d8e3a6504
141 changed files with 3937 additions and 1815 deletions

199
eo/src/obsolete/eo1d.h Normal file
View file

@ -0,0 +1,199 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eo1d.h
Serial EO.
(c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#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
*/
//@{
/**
@deprecated {eo1d} eo1d
\deprecated
*/
/**
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,
\deprecated
As eo1d provides a so-called 'fat' interface, it might be wiser to
use eoFixedLength or eoVariableLength instead, that derive from
vector and list respectively and (important) redirect the less than
comparison operator to EO rather than the STL variants.
@see eoFixedLength eoVariableLength
*/
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, subclasses should
have to implement this.
@param _is the input stream
*/
eo1d( istream& _is): EO<fitnessT>(){ readFrom(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 getGene( 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 void setGene( unsigned _i, const T& _value ) = 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 ++ ) {
T tmp;
_s >> tmp;
setGene( i, tmp );
}
// there is no way of distinguishing fitness from the object, so
// it's skipped
}
/** Print itself: inherited from eoObject implementation.
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 << getGene( 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

View file

@ -0,0 +1,136 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eo1dWDistance.h
Serial EO with distances. Acts as a wrapper for normal eo1ds
(c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EO1DWDISTANCE_H
#define _EO1DWDISTANCE_H
#include <iostream> // for ostream
// EO Includes
#include <eo1d.h>
#include <eoDistance.h>
using namespace std;
/** eo1dWDistance: wraps around eo1ds and adds the possibility of computing distances
around them.
*/
template<class T, class fitnessT = float>
class eo1dWDistance:
public eo1d< T,fitnessT >,
public eoDistance<eo1d<T,fitnessT> > {
public:
/** Can be used as default ctor; should be called from derived
classes. Fitness should be at birth
*/
eo1dWDistance( eo1d<T,fitnessT>& _eo)
:eo1d<T,fitnessT> (), eoDistance< eo1d<T,fitnessT> >(), innereo1d( _eo ) {};
/// Needed virtual dtor
virtual ~eo1dWDistance(){};
/** 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 getGene( unsigned _i ) const {
return innereo1d.getGene( _i );
};
/** 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 void setGene( unsigned _i, const T& _value ) {
innereo1d.setGene( _i, _value);
};
/** 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 ) {
innereo1d.insertGene( _i, _val);
}
/** 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 ) {
innereo1d.deleteGene( _i );
}
/// Returns the number of genes in the eo1d
virtual unsigned length() const {
return innereo1d.length();
}
/// Returns the distance from this EO to the other
virtual double distance( const eo1d<T,fitnessT>& _eo ) const {
double tmp = 0;
// Which one is shorter
unsigned len = (innereo1d.length() < _eo.length()) ? _eo.length():innereo1d.length();
// Compute over the whole length. If it does not exists, it counts as 0
for ( unsigned i = 0; i < len; i ++ ) {
T val1, val2;
val1 = ( i > innereo1d.length())?0:innereo1d.getGene(i);
val2 = ( i > _eo.length() )?0:_eo.getGene(i);
double diff = val1 - val2;
tmp += diff*diff;
}
return tmp;
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eo1dWDistance";};
//@}
private:
///Private ctor. Do not use
eo1dWDistance() {};
eo1d<T,fitnessT>& innereo1d;
};
//@}
#endif

242
eo/src/obsolete/eo2d.h Normal file
View file

@ -0,0 +1,242 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
/*
-----------------------------------------------------------------------------
File............: eo2d.h
Author..........: Geneura Team (this file: Victor Rivas, vrivas@ujaen.es)
Date............: 21-Sep-1999, at Fac. of Sciences, Univ. of Granada (Spain)
Description.....: Implementation of a 2-dimensional chromosome.
================ Modif. 1 ================
Author........:
Date..........:
Description...:
-----------------------------------------------------------------------------
*/
//-----------------------------------------------------------------------------
// eo2d.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EO2D_H
#define _EO2D_H
#include <iostream> // for ostream
#include <vector>
// EO Includes
#include <EO.h>
#include <eoRnd.h>
using namespace std;
/** @name eo2d class
* Randomly accesible evolvable object with two dimension, with
variable length each of them.
* Use this if you want to evolve "two-dimensional" things, like bit arrays, or
floating-point arrays. If you don't, subclass directly from EO
* @see EO
* @author GeNeura
* @version 0.2
*/
//@{
/** eo2d: Base class for "chromosomes" with a double 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 eo2d: 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
*/
eo2d()
:EO<fitnessT> ( ) {};
/** Ctor using a random number generator and with an specified size
@param _rows Initial number of rows
@param _columns Initial number of columns
@param _rndGen Random "T-type" generator
@param _ID An ID string, preferably unique
*/
eo2d( const unsigned _rows,
const unsigned _columns,
eoRnd<T>& _rndGen,
const string& _ID = "");
/** Ctor from an istream. It just passes the stream to EO, subclasses should
have to implement this.
@param _is the input stream
*/
eo2d( istream& _is): EO<fitnessT>( _is ){};
/// Copy ctor
eo2d( const eo2d& _eo )
:EO<fitnessT> ( _eo ) {};
/// Assignment operator
const eo2d& operator= ( const eo2d& _eo ) {
EO<fitnessT>::operator = ( _eo );
return *this;
}
/// Needed virtual dtor
virtual ~eo2d(){};
/** Reads and returns a copy of the gene in position _r,_c.\
This implies that T must have a copy ctor .
@param _r Index for rows. Must be an unsigned less than #numOfRows()#
@param _c Index for columns. Must be an unsigned less than #numOfCols()#
@return what's inside the gene, with the correct type
@exception out_of_range if _r >=numOfRows()
@exception out_of_range if _c >=numOfCols()
*/
virtual T getGene( const unsigned _r,
const unsigned _j ) const = 0;
/** Overwrites the gene placed in position _r,_c with a
* new value. This means that the assignment operator
* for T must be defined .
@param _r Index for rows. Must be an unsigned less than #numOfRows()#
@param _c Index for columns. Must be an unsigned less than #numOfCols()#
@return what's inside the gene, with the correct type
@exception out_of_range if _r >=numOfRows()
@exception out_of_range if _c >=numOfCols()
*/
virtual void setGene( const unsigned _r,
const unsigned _c,
const T& _value ) = 0;
/** Inserts a row, moving the rest to the bottom.
* If _r = numOfRows(), it insert it at the end.
* Obviously, changes number of rows.
@param _r Position where the new row will be inserted.
@param _val Vector containing the new values to be inserted.
@exception invalid_argument If _val has not numOfCols() components.
@exception out_of_range If _r is greater than numOfRows()
*/
virtual void insertRow( const unsigned _r,
const vector<T>& _val ) = 0;
/** Eliminates the row at position _r; all the other genes will
be shifted up.
@param _r Number of he row to be deleted.
@exception out_of_range if _r >=numOfRows()
*/
virtual void deleteRow( const unsigned _r ) = 0;
/** Inserts a column, moving the rest to the right.
* If _c = numOfCols(), it insert it at the end.
* Obviously, changes number of cols.
@param _r Position where the new column will be inserted.
@param _val Vector containing the new values to be inserted.
@exception invalid_argument if _val has not numOfRows() components.
*/
virtual void insertCol( const unsigned _c,
const vector<T>& _val ) = 0;
/** Eliminates the column at position _c; all the other columns will
be shifted left.
@param _c Number of he column to be deleted.
@exception out_of_range if _c >=numOfCols()
*/
virtual void deleteCol( const unsigned _c ) = 0;
/// Returns the number of rows in the eo2d
virtual unsigned numOfRows() const = 0;
/// Returns the number of columns in the eo2d
virtual unsigned numOfCols() 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 r = 0; r < numOfRows(); ++r ) {
for ( unsigned c = 0; c < numOfCols(); ++c ) {
T tmp;
_s >> tmp;
setGene( r, c, tmp );
}
}
// there is no way of distinguishing fitness from the object, so
// it's skipped
}
/** Print itself: inherited from eoObject implementation.
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 r = 0; r < numOfRows(); ++r ) {
for ( unsigned c = 0; c < numOfCols(); ++c ) {
_s << getGene( r,c ) << " ";
}
}
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eo2d";};
//@}
};
//@}
// --------------- Implementations --------------------------
/** Ctor using a random number generator and with an specified size
@param _rows Initial number of rows
@param _columns Initial number of columns
@param _rndGen Random "T-type" generator
@param _ID An ID string, preferably unique
*/
template< class T, class fitnessT>
eo2d<T,fitnessT>::eo2d<T,fitnessT>( const unsigned _rows,
const unsigned _columns,
eoRnd<T>& _rndGen,
const string& _ID = "")
:EO<fitnessT> ( _ID ) {
for ( unsigned r = 0; r < _rows; ++r ) {
for ( unsigned c = 0; c < _cols; ++c ) {
insertGene( r, c, _rndGen() );
}
}
};
#endif

View file

@ -0,0 +1,334 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
/*
-----------------------------------------------------------------------------
File............: eo2dVector.h
Author..........: Geneura Team (this file: Victor Rivas, vrivas@ujaen.es)
Date............: 29-Sep-1999, at Fac. of Sciences, Univ. of Granada (Spain)
Description.....: Implementation of a 2-dimensional chromosome usign STL
vectors.
================ Modif. 1 ================
Author........:
Date..........:
Description...:
QUEDA: Operador de asignación, lectura desde istream, escritura a ostream
-----------------------------------------------------------------------------
*/
//-----------------------------------------------------------------------------
// eo2dVector.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _eo2dVector_H
#define _eo2dVector_H
// STL libraries
#include <vector> // For vector<int>
#include <stdexcept>
#include <strstream>
#include <iostream.h>
#include <eo2d.h>
#include <eoRnd.h>
/** Adaptor that turns an STL vector of vectror into an EO
with the same gene type as the type with which
the vector of vector has been instantiated.
*/
template <class T, class fitnessT>
class eo2dVector: public eo2d<T, fitnessT>, public vector< vector<T> > {
public:
typedef T Type ;
/** @name Canonical part of the objects: several ctors, copy ctor, \
* dtor and assignment operator.
*/
//@{
/** Ctor.
@param _rows Number of rows.
@param _cols Number of columns.
@param _val Common initial value
*/
eo2dVector( const unsigned _rows = 0,
const unsigned _cols = 0,
T _val = T() )
: eo2d<T, fitnessT>(), vector< vector<T> >( _rows, vector<T>( _cols, _val ) ){};
/** Ctor using a random number generator.
@param _rows Number of rows.
@param _cols Number of columns.
@param _rnd A random "T-type" generator, which returns a random value each time it´s called.
*/
eo2dVector( const unsigned _rows,
const unsigned _cols,
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
*/
//eo2dVector( istream& _is);
/// copy ctor
eo2dVector( const eo2dVector & _eo )
: eo2d<T, fitnessT>( _eo ), vector< vector<T> >( _eo ){ };
/// Assignment operator
/*
const eo2dVector& operator =( const eo2dVector & _eo ) {
if ( this != &_eo ){
eo2d<T, fitnessT>::operator=( _eo );
vector< <vector<T> >::operator=( _eo );
}
return *this;
}
*/
/// dtor
virtual ~eo2dVector() {};
//@}
/** Reads and returns a copy of the gene in position _r,_c.\
This implies that T must have a copy ctor .
@param _r Index for rows. Must be an unsigned less than #numOfRows()#
@param _c Index for columns. Must be an unsigned less than #numOfCols()#
@return what's inside the gene, with the correct type
@exception out_of_range if _r >=numOfRows()
@exception out_of_range if _c >=numOfCols()
*/
virtual T getGene( const unsigned _r,
const unsigned _c ) const {
if ( _r >= numOfRows() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::getGene: row out of range. "
<< "It should be <" << numOfRows() << '\0' << endl;
throw out_of_range( msg.str() );
}
if ( _c >= numOfCols() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::getGene: column out of range. "
<< "It should be <" << numOfCols() << '\0' << endl;
throw out_of_range( msg.str() );
}
return (*this)[_r][_c];
};
/** Overwrites the gene placed in position _r,_c with a
* new value. This means that the assignment operator
* for T must be defined .
@param _r Index for rows. Must be an unsigned less than #numOfRows()#
@param _c Index for columns. Must be an unsigned less than #numOfCols()#
@return what's inside the gene, with the correct type
@exception out_of_range if _r >=numOfRows()
@exception out_of_range if _c >=numOfCols()
*/
virtual void setGene( const unsigned _r,
const unsigned _c,
const T& _value ) {
if ( _r >= numOfRows() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::setGene: row out of range. "
<< "It should be <" << numOfRows() << '\0' << endl;
throw out_of_range( msg.str() );
}
if ( _c >= numOfCols() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::setGene: column out of range. "
<< "It should be <" << numOfCols() << '\0' << endl;
throw out_of_range( msg.str() );
}
(*this)[_r][_c]=_value;
};
/** Inserts a row, moving the rest to the bottom.
* If _r = numOfRows(), it insert it at the end.
* Obviously, changes number of rows.
@param _r Position where the new row will be inserted.
@param _val Vector containing the new values to be inserted.
@exception invalid_argument If _val has not numOfCols() components.
@exception out_of_range If _r is greater than numOfRows()
*/
virtual void insertRow( const unsigned _r,
const vector<T>& _val ) {
// Test errors.
if ( _r > numOfRows() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::insertRow: row out of range. "
<< "It should be <=" << numOfRows() << '\0' << endl;
throw out_of_range( msg.str() );
}
if ( _val.size() != numOfCols() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::insertRow: "
<< "Incorrect number of values to be added. "
<< "It should be ==" << numOfCols() << '\0' << endl;
throw invalid_argument( msg.str() );
}
// Insert the row.
vector< vector<T> >::iterator ite = begin()+_r;
insert( ite, _val );
};
/** Eliminates the row at position _r; all the other genes will
be shifted up.
@param _r Number of he row to be deleted.
@exception out_of_range if _r >=numOfRows()
*/
virtual void deleteRow( const unsigned _r ) {
// Test error.
if ( _r >= numOfRows() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::deleteRow: "
<< "Row out of range. "
<< "It should be <" << numOfRows() << '\0' << endl;
throw out_of_range( msg.str() );
}
// Delete row.
vector< vector<T> >::iterator ite = this->begin()+_r;
this->erase( ite );
};
/** Inserts a column, moving the rest to the right.
* If _c = numOfCols(), it insert it at the end.
* Obviously, changes number of cols.
@param _r Position where the new column will be inserted.
@param _val Vector containing the new values to be inserted.
@exception invalid_argument if _val has not numOfRows() components.
*/
virtual void insertCol( const unsigned _c,
const vector<T>& _val ) {
// Test errors.
if ( _c > numOfCols() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::insertCol: "
<< "Column out of range. "
<< "It should be >=" << numOfCols() << '\0' << endl;
throw out_of_range( msg.str() );
}
if ( _val.size() != numOfRows() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::insertCol: "
<< "Incorrect number of values to be added. "
<< "It should be ==" << numOfRows() << '\0' << endl;
throw invalid_argument( msg.str() );
}
// Insert column.
for( unsigned r=0; r<numOfRows(); ++r ) {
vector<vector<T> >::iterator it1 = begin()+r;
vector<T>::iterator it2 = (*it1).begin()+_c;
(*it1).insert( it2, _val[r] );
};
}
/** Eliminates the column at position _c; all the other columns will
be shifted left.
@param _c Number of he column to be deleted.
@exception out_of_range if _c >=numOfCols()
*/
virtual void deleteCol( const unsigned _c ) {
// Test error.
if ( _c >= numOfCols() ) {
ostrstream msg;
msg << "ERROR in eo2dVector::deleteCol: "
<< "Column out of range. "
<< "It should be <" << numOfCols() << '\0' << endl;
throw out_of_range( msg.str() );
}
// Delete columns.
for( unsigned r=0; r<numOfRows(); ++r ) {
vector<vector<T> >::iterator it1 = begin()+r;
vector<T>::iterator it2 = (*it1).begin()+_c;
(*it1).erase( it2 );
}
};
/// Returns the number of rows in the eo2d
virtual unsigned numOfRows() const {
return size();
};
/// Returns the number of columns in the eo2d
virtual unsigned numOfCols() const {
return begin()->size();
};
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eo2dVector";};
//@}
};
//____________________________ Some method implementation ____________________
// Ctors_______________________________________________________________________
//_____________________________________________________________________________
template <class T, class fitnessT>
eo2dVector<T,fitnessT>::eo2dVector( const unsigned _rows,
const unsigned _cols,
eoRnd<T>& _rnd )
: eo2d<T, fitnessT>(), vector< vector<T> >( _rows, vector<T>( _cols, T() ) ){
for ( vector< vector<T> >::iterator i = begin(); i != end(); ++i ) {
for( vector<T>::iterator j=(*i).begin(); j!= (*i).end(); ++j ) {
*j = _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 );
}
};
*/
//_____________________________________________________________________________
template <class T, class fitnessT>
ostream& operator<<( ostream& _os, const eo2dVector<T,fitnessT>& _eo) {
for( unsigned i=0; i<_eo.numOfRows(); ++i ) {
for( unsigned j=0; j<_eo.numOfCols(); ++j ) {
_os << _eo.getGene( i,j ) << " ";
}
_os << endl;
}
return _os;
};
#endif

View file

@ -0,0 +1,58 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoAtomBitFlip.h
// Increments or decrements by one a single element
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOATOMBITFLIP_H
#define _EOATOMBITFLIP_H
/** Flips a single bit
*/
template <class T>
class eoAtomBitFlip: public eoAtomMutator<bool> {
public:
///
eoAtomBitFlip() {};
///
virtual ~eoAtomBitFlip() {};
///
virtual void operator()( T& _val ) const {
_val = !val;
}
/** @name Methods from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoAtomBitFlip";};
//@}
};
#endif

View file

@ -0,0 +1,66 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoAtomCreep.h
// Increments or decrements by one a single element
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOATOMCREEP_H
#define _EOATOMCREEP_H
#include <utils/eoRNG.h>
#include <eoAtomMutator.h>
/** With uniform probability, decrements or increments by one the value.
The value type must admit post increment and decrement.
*/
template <class T>
class eoAtomCreep: public eoAtomMutator<T> {
public:
///
eoAtomCreep() {};
///
virtual ~eoAtomCreep() {};
///
virtual void operator()( T& _val ) const {
if ( rng.flip( 0.5 ) ) {
_val++;
} else {
_val--;
}
}
/** @name Methods from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoAtomCreep";};
//@}
};
#endif

View file

@ -0,0 +1,95 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoAtomMutation.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOATOMMUTATION_H
#define _EOATOMMUTATION_H
// STL includes
#include <iterator>
// EO includes
#include <eoOp.h>
#include <utils/eoRNG.h>
#include <eoAtomMutator.h>
/** Atomic mutation of an EO. Acts on containers, and applies a mutation
operator to each element of the container with some probability. EOT must
be a container of any type
*/
template <class EOT>
class eoAtomMutation: public eoMonOp<EOT> {
public:
#ifdef _MSC_VER
typedef EOT::Type Type;
#else
typedef typename EOT::Type Type;
#endif
///
eoAtomMutation(const eoAtomMutator<Type>& _atomMut, const double _rate=0.0)
: eoMonOp< EOT >(), rate(_rate), atomMutator( _atomMut ) {};
///
virtual ~eoAtomMutation() {};
///
virtual void operator()( EOT& _eo ) const {
typename EOT::iterator i;
for ( i = _eo.begin(); i != _eo.end(); i ++ )
if ( rng.flip( rate ) ) {
atomMutator( *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";};
//@}
private:
double rate;
const eoAtomMutator<Type>& atomMutator;
};
#endif

View file

@ -0,0 +1,40 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoAtomMutator.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOATOMMUTATOR_H
#define _EOATOMMUTATOR_H
#include <eoFunctor.h>
/** Abstract base class for functors that modify a single element in an EO
that is composed of several atomic components. An atom would, for instance, flip
a bit, or change a real number, or things like that. The header is completely
empty and thus just provides a name rather than functionality.
*/
template <class T>
class eoAtomMutator: public eoUnaryFunctor<void, T&> {};
#endif

View file

@ -0,0 +1,64 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoAtomRandom.h
Increments or decrements by one a single element
(c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOATOMRANDOM_H
#define _EOATOMRANDOM_H
#include <eoRnd.h>
/** Modifies using a random number generator, that is entered in the ctor.
The RNG must return positive or negative numbers, whatever.
*/
template <class T>
class eoAtomRandom: public eoAtomMutator<T> {
public:
///
eoAtomRandom( eoRnd<T>& _rng): rnd( _rng ) {};
///
virtual ~eoAtomRandom() {};
/// Adds the value generated by the RNG to the former value
virtual void operator()( T& _val ) const {
_val += rnd();
}
/** @name Methods from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoAtomRandom";};
//@}
private:
eoRnd<T>& rnd;
};
#endif

89
eo/src/obsolete/eoBin.h Normal file
View file

@ -0,0 +1,89 @@
/*
eoBin.h
(c) GeNeura Team 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
#ifndef eoBin_h
#define eoBin_h
//-----------------------------------------------------------------------------
#include <iostream> // ostream, istream
#include <functional> // bind2nd
#include <string> // string
#include <eoFixedLength.h>
/**
\defgroup bitstring
Various functions for a bitstring representation
*/
/** eoBin: implementation of binary chromosome.
\class eoBin eoBin.h ga/eoBin.h
\ingroup bitstring
* based on STL's bit_vector (vector<bool>).
*/
template <class F> class eoBin: public eoFixedLength<F, bool>
{
public:
/**
* (Default) Constructor.
* @param size Size of the binary string.
*/
eoBin(unsigned size = 0, bool value = false):
eoVector<bool,F>(size, value) {}
/// 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'));
}
}
};
//-----------------------------------------------------------------------------
#endif eoBin_h

116
eo/src/obsolete/eoBreeder.h Normal file
View file

@ -0,0 +1,116 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoBreeder.h
// Takes two populations and mixes them
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef eoBreeder_h
#define eoBreeder_h
//-----------------------------------------------------------------------------
#include <vector> // vector
#include <utils/eoRNG.h>
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include <eoPop.h> // eoPop
#include <eoOpSelector.h> // eoOpSelector
#include <eoFunctor.h>
#include <eoRandomIndiSelector.h>
#include <eoBackInserter.h>
using namespace std;
/*****************************************************************************
* eoBreeder: transforms a population using genetic operators. *
* For every operator there is a rated to be applyed. *
*****************************************************************************/
template<class Chrom> class eoBreeder: public eoTransform<EOT>
//eoUnaryFunctor<void, eoPop<Chrom>&>
{
public:
/// Default constructor.
eoBreeder( eoOpSelector<Chrom>& _opSel): opSel( _opSel ) {}
/// Destructor.
virtual ~eoBreeder() {}
/**
* Transforms a population.
* @param pop The population to be transformed.
*/
void operator()(eoPop<Chrom>& pop)
{
size_t orgsize = pop.size();
for (unsigned i = 0; i < pop.size(); i++)
{
eoOp<Chrom>* op = opSel.Op();
switch (op->getType())
{
case eoOp<Chrom>::unary:
{
eoMonOp<Chrom>* monop = static_cast<eoMonOp<Chrom>* >(op);
(*monop)( pop[i] );
break;
}
case eoOp<Chrom>::binary:
{
eoBinOp<Chrom>* binop = static_cast<eoBinOp<Chrom>* >(op);
(*binop)(pop[i], pop[ rng.random(pop.size()) ] );
break;
}
case eoOp<Chrom>::quadratic:
{
eoQuadraticOp<Chrom>* Qop = static_cast<eoQuadraticOp<Chrom>* >(op);
(*Qop)(pop[i], pop[ rng.random(pop.size()) ] );
break;
}
case eoOp<Chrom>::general :
{
eoGeneralOp<Chrom>* Gop = static_cast<eoGeneralOp<Chrom>* >(op);
eoRandomIndiSelector<Chrom> selector;
eoBackInserter<Chrom> inserter;
(*Gop)(selector.bind(pop, orgsize).bias(i), inserter.bind(pop));
break;
}
}
}
};
/// The class name.
string className() const { return "eoBreeder"; }
private:
eoOpSelector<Chrom>& opSel;
};
//-----------------------------------------------------------------------------
#endif eoBreeder_h

View file

@ -0,0 +1,58 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoDetTournamentIndiSelector.h
(c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
#ifndef eoDetTournamentIndiSelector_h
#define eoDetTournamentIndiSelector_h
#include "eoIndiSelector.h"
#include "utils/selectors.h"
/**
\ingroup selectors
* eoDetTournamentIndiSelector: selects children through a deterministic_tournament
*/
template <class EOT>
class eoDetTournamentIndiSelector : public eoPopIndiSelector<EOT>
{
public :
eoDetTournamentIndiSelector(int _tournamentSize)
: eoPopIndiSelector<EOT>(),
tournamentSize(_tournamentSize)
{}
virtual ~eoDetTournamentIndiSelector(void) {}
const EOT& do_select(void)
{
return *deterministic_tournament(begin(), end(), tournamentSize);
}
private :
int tournamentSize;
};
#endif

View file

@ -0,0 +1,63 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoObject.h
This is the base class for most objects in EO. It basically defines an interf
face for giving names to classes.
(c) GeNeura Team, 1998, 1999, 2000
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef EODISTANCE_H
#define EODISTANCE_H
//-----------------------------------------------------------------------------
using namespace std;
//-----------------------------------------------------------------------------
// eoDistance
//-----------------------------------------------------------------------------
/** Defines an interface for measuring distances between evolving objects */
template <class EOT>
class eoDistance {
public:
/// Default Constructor.
eoDistance() {}
/// Copy constructor.
eoDistance( const eoDistance& ) {}
/// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoDistance() {}
/** Return the distance from the object with this interface to other
object of the same type.
*/
virtual double distance( const EOT& ) const = 0;
/// Returns classname
virtual string className() const { return "eoDistance"; }
};
#endif EOOBJECT_H

70
eo/src/obsolete/eoDup.h Normal file
View file

@ -0,0 +1,70 @@
// eoDup.h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoKill.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EODUP_h
#define _EODUP_h
#include <utils/eoRNG.h>
#include <eoOp.h>
/// Dup or duplicate: duplicates a gene in a chromosome
template <class FitT, class Atomic>
class eoDup: public eoMonOp<eoVariableLength<FitT, Atomic> > {
public:
///
eoDup( )
: eoMonOp< EOT >( ){};
/// needed virtual dtor
virtual ~eoDup() {};
///
virtual void operator()(eoVariableLength<FitT, Atomic>& _eo ) const
{
unsigned pos = rng.random(_eo.size());
eoVariableLength<FitT, Atomic>::iterator it = begin();
while (pos--) {++it;}
_eo.insert(it, 1, *it);
_eo.invalidate();
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoDup";};
//@}
};
#endif

164
eo/src/obsolete/eoES.h Normal file
View file

@ -0,0 +1,164 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoESChrom.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#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
*/
//@{
/**
\class eoESValue
*/
template <class T>
struct eoESValue
{
T value;
/**
The gene has a mutate member because this particular gaussian mutation
is paradigmatic for an evolution strategy.
*/
void mutate(double sigma, T minimum = T(), T maximum = T())
{
value += rng.normal(0.0, sigma);
if (minimum > value)
value = minimum;
if (value > maximum)
value = maximum;
}
};
/**
\class eoESGene eoESGene.h es/eoESGene.h
Each gene in an Evolution Strategies is composed of a value plus an standard
deviation, sigma, used for mutation*/
template <class T>
struct eoESGene : public eoESValue<T>
{
double sigma;
eoESGene( double _val = 0, double _sigma = 1.0 ): eoESValue( _val ), sigma( _sigma ) {};
/**
The gene has a mutate member because the sigma member implies
that the updating routine should use a normal distribution
*/
void mutate(T minimum, T maximum)
{
mutate(sigma, minimum, maximum);
}
};
/// 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

164
eo/src/obsolete/eoESChrom.h Normal file
View file

@ -0,0 +1,164 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoESChrom.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#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
*/
//@{
/**
\class eoESValue
*/
template <class T>
struct eoESValue
{
T value;
/**
The gene has a mutate member because this particular gaussian mutation
is paradigmatic for an evolution strategy.
*/
void mutate(double sigma, T minimum, T maximum)
{
value += rng.normal(0.0, sigma);
if (minimum > value)
value = minimum;
if (value > maximum)
value = maximum;
}
};
/**
\class eoESGene eoESGene.h es/eoESGene.h
Each gene in an Evolution Strategies is composed of a value plus an standard
deviation, sigma, used for mutation*/
template <class T>
struct eoESGene : public eoESValue<T>
{
double sigma;
eoESGene( double _val = 0, double _sigma = 1.0 ): eoESValue( _val ), sigma( _sigma ) {};
/**
The gene has a mutate member because the sigma member implies
that the updating routine should use a normal distribution
*/
void mutate(T minimum, T maximum)
{
mutate(sigma, minimum, maximum);
}
};
/// 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

View file

@ -0,0 +1,267 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoESInd.h
// (c) GeNeura Team, 1998 - EEAAX 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
*/
//-----------------------------------------------------------------------------
#ifndef _EOESFULLCHROM_H
#define _EOESFULLCHROM_H
// STL libraries
#include <vector> // For vector<>
#include <stdexcept>
#include <strstream>
#include <iostream> // for ostream
// EO includes
#include <eoVector.h>
#include <utils/eoRNG.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 and a vector of correlations
*/
//@{
/**@name individuals for evolution strategies -MS- 22/10/99
Each individual in an evolution strategy is composed of
a vector of floating point values
a vector of std deviations
a vector of rotation angles (for correlated mutations)
These individuals CANNOT BE IMPLEMENTED as vectors of anything
at least in the case of correlated mutations
*/
//@{
template <typename fitT = float >
class eoESFullChrom : public eoVector<double, fitT> {
public:
/// constructor
eoESFullChrom( unsigned _num_genes = 1,
unsigned _num_sigma = 1, unsigned _num_correl = 0,
bool _verbose = false,
double _ObjMin = 0, double _ObjMax = 1,
double _StdDevInit = 0.3 ):
eoVector<double, fitT>(_num_genes),
// ObjVar( _num_genes ), now an eoVector<double>
StdDev( _num_sigma ),
CorCff( _num_correl ),
verbose( _verbose ),
ObjMin( _ObjMin ),
ObjMax(_ObjMax ),
StdDevInit( _StdDevInit )
{ // check consistency
}
/* And now the useful constructor: from a parser (should be in the
factory, if such a thing exists one day for eoESFullChrom
*/
eoESFullChrom(eoParser & parser) : StdDev(0), CorCff(0) {
parser.AddTitle("Description of ES individuals");
int num_genes, num_sigma;
bool correlated_mutations;
try {
num_genes = parser.getInt("-Io", "--NbObjVar", "2",
"Number of Object Variables" );
num_sigma = parser.getInt("-Is", "--NbSigma", "1",
"Number of Standard Deviations" );
correlated_mutations = parser.getBool("-Ic", "--Correlated",
"Correlated mutation?" );
ObjMin = parser.getFloat("-Im", "--min", "0",
"Minimum value for object variables" );
ObjMax = parser.getFloat("-IM", "--max", "1",
"Maximum value for object variables" );
StdDevInit = parser.getFloat("-II", "--SigmaInit", "0.3",
"Initial value for std. dev. (scaled by range)" );
verbose = parser.getBool("-Iv", "--verbose",
"Verbose listing of ES individuals (mutation parameters");
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
// consistency tests
if (! num_sigma) { // no std dev??? EXCEPTION
throw invalid_argument( "No standard deviation: choose another representation please" );
}
if (num_sigma > num_genes) {
cout << "WARNING, Number of Standard Deviations > Number of Object Variables\nAdjusted!\n";
num_sigma = num_genes;
// modify the Param value - so .status is OK
ostrstream sloc;
sloc << num_genes;
parser.setParamValue("--NbSigma", sloc.str());
}
// adjust the sizes!!!
resize(num_genes);
if (num_sigma)
StdDev.resize(num_sigma);
if (correlated_mutations) {
if (num_sigma < num_genes) {
cout << "WARNING less Std Dev. than number of variables + Correlated mutations\n";
cout << "Though possible, this is a strange setting" << endl;
}
// nb of rotation angles: N*(N-1)/2 (in general!)
CorCff.resize ( (2*num_genes - num_sigma)*(num_sigma - 1) / 2 );
}
};
/// Operator =
const eoESFullChrom& operator = ( const eoESFullChrom& _eo ) {
if ( this != &_eo ) {
// Change EO part
eoVector<double, fitT>::operator = (_eo);
// Change this part
// ObjVar = _eo.ObjVar;
StdDev = _eo.StdDev;
CorCff = _eo.CorCff;
verbose = _eo.verbose;
ObjMin = _eo.ObjMin;
ObjMax = _eo.ObjMax;
StdDevInit = _eo.StdDevInit;
}
return *this;
}
/// destructor
virtual ~eoESFullChrom() {}
///
double getStdDev( unsigned _i ) const {
if ( _i >= length() )
throw out_of_range( "out_of_range when reading StdDev");
return StdDev[ _i ];
}
///
void setStdDev( unsigned _i, double _val ) {
if ( _i < length() ) {
StdDev[_i] = _val;
} else
throw out_of_range( "out_of_range when writing StdDev");
}
///
double getCorCff( unsigned _i ) const {
if ( _i >= length() )
throw out_of_range( "out_of_range when reading CorCff");
return CorCff[ _i ];
}
///
void setCorCff( unsigned _i, double _val ) {
if ( _i < length() ) {
CorCff[_i] = _val;
} else
throw out_of_range( "out_of_range when writing CorCff");
}
///
void insertGene( unsigned _i, double _val ) {
throw FixedLengthChromosome();
};
///
void deleteGene( unsigned _i ) {
throw FixedLengthChromosome();
};
///
unsigned length() const { return size();}/* formerly ObjVar.size() */
unsigned StdDevLength() const { return StdDev.size();}
unsigned CorCffLength() const { return CorCff.size();}
/** Print itself: inherited from eoObject implementation.
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{
copy( begin(), end(), ostream_iterator<double>( _s, " ") );
// The formatting instructinos shoudl be left to the caller
// _s << "\n";
if (verbose) {
_s << "\n\tStd Dev. " ;
copy( StdDev.begin(), StdDev.end(), ostream_iterator<double>( _s, " ") );
if (CorCff.size()) {
_s << "\n\t";
copy( CorCff.begin(), CorCff.end(), ostream_iterator<double>( _s, " ") );
}
}
};
/** This exception should be thrown when trying to insert or delete a gene
in a fixed length chromosome
*/
class FixedLengthChromosome : public exception {
public:
/**
* Constructor
*/
FixedLengthChromosome()
: exception() { };
~FixedLengthChromosome() {};
};
// accessors
double getObjMin() const {return ObjMin;}
double getObjMax() const {return ObjMax;}
double getStdDevInit () const {return StdDevInit;}
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoESFullChrom";};
private:
// vector<double> ObjVar; /* object variable vector */
// or shoudl the class be subclass of EOVector<double> ???
vector<double> StdDev; /* standard deviation vector */
vector<double> CorCff; /* correlation coefficient vector */
bool verbose; /* Print std deviations or not */
/** the range is used for mutation AND random initialization,
* while the StdDevInit is used only for random initialization
* this in a little inconsistent!
*/
double ObjMin, ObjMax; /* Range for Object variables */
double StdDevInit; /* Initial value of Standard Deviations */
};
#endif

View file

@ -0,0 +1,261 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoESMute.h : ES mutation
// (c) Maarten Keijzer 2000 & GeNeura Team, 1998 for the EO part
// Th. Baeck 1994 and EEAAX 1999 for the ES part
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
marc.schoenauer@polytechnique.fr
http://eeaax.cmap.polytchnique.fr/
*/
//-----------------------------------------------------------------------------
#ifndef _EOESMUT_H
#define _EOESMUT_H
#include <utils/eoParser.h>
#include <utils/eoRNG.h>
#include <cmath> // for exp
#include <es/eoESFullChrom.h>
#include <es/eoESInit.h>
#include <eoOp.h>
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
/** ES-style mutation in the large: Obviously, valid only for eoES*
It is currently valid for three types of ES chromosomes:
eoEsSimple: only 1 std deviation
eoEsStdev: as many standard deviations as object variables
eoEsFull: The whole guacemole: correlations, stdevs and object variables
Each of these three variant has it's own operator() in eoEsMutate
*/
template <class EOT>
class eoESMutate: public eoMonOp< EOT > {
public:
typedef EOT::Fitness FitT;
/** Initialization
parameters:
@param _init proxy class for initializating the three parameters eoEsMutate needs
@param _bounds the bounds for the objective variables
*/
eoESMutate(eoESMutationInit& _init, eoESObjectiveBounds& _bounds) : bounds(_bounds)
{
unsigned size = bounds.chromSize();
if (eoEsInfo<EOT>::single_stdev)
{
TauLcl = _init.TauLcl();
TauLcl /= sqrt((double) size);
}
else
{
TauLcl = _init.TauLcl();
TauGlb = _init.TauGlb();
// renormalization
TauLcl /= sqrt( 2.0 * sqrt( (double)size ) );
TauGlb /= sqrt( 2.0 * ( (double) size ) );
if (eoEsInfo<EOT>::has_correlation)
{ // Correlated Mutations
TauBeta = _init.TauBeta();
}
}
}
/// needed virtual dtor
virtual ~eoESMutate() {};
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoESMutate";};
/**
Mutate eoEsSimple
*/
virtual void operator()( eoEsSimple<FitT>& _eo) const
{
_eo.stdev *= exp(TauLcl * rng.normal());
if (_eo.stdev < eoEsInfo<EOT>::stdev_eps)
_eo.stdev = eoEsInfo<EOT>::stdev_eps;
// now apply to all
for (unsigned i = 0; i < _eo.size(); ++i)
{
_eo[i] += _eo.stdev * rng.normal();
}
keepInBounds(_eo);
}
/// mutations - standard and correlated
// =========
/*
* Standard mutation of object variables and standard
* deviations in ESs.
* If there are fewer different standard deviations available
* than the dimension of the objective function requires, the
* last standard deviation is responsible for ALL remaining
* object variables.
* Schwefel 1977: Numerische Optimierung von Computer-Modellen
* mittels der Evolutionsstrategie, pp. 165 ff.
*/
virtual void operator()( eoESStdev<FitT>& _eo ) const
{
double global = exp(TauGlb * rng.normal());
for (unsigned i = 0; i < _eo.size(); i++)
{
double stdev = _eo.stdevs[i];
stdev *= global * exp(TauLcl * rng.normal());
if (stdev < eoEsInfo<EOT>::stdev_eps)
stdev = eoEsInfo<EOT>::stdev_eps;
_eo.stdevs[i] = stdev;
_eo[i] += stdev * rng.normal();
}
keepInBounds(_eo);
}
/*
* Correlated mutations in ESs, according to the following
* sources:
* H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80
* p. 43, 1980
* G. Rudolph: Globale Optimierung mit parallelen Evolutions-
* strategien, Diploma Thesis, University of Dortmund, 1990
*/
// Code from Thomas Baeck
virtual void operator()( eoEsFull<fitT> & _eo ) const
{
/*
* First: mutate standard deviations (as above).
*/
double global = exp(TauGlb * rng.normal());
for (unsigned i = 0; i < _eo.size(); i++)
{
double stdev = _eo.stdevs[i];
stdev *= global * exp(TauLcl * rng.normal());
if (stdev < eoEsInfo<EOT>::stdev_eps)
stdev = eoEsInfo<EOT>::stdev_eps;
_eo.stdevs[i] = stdev;
}
/*
* Mutate rotation angles.
*/
for (i = 0; i < _eo.correlations.size(); i++)
{
_eo.correlations[i] += TauBeta * rng.normal();
if ( fabs(_eo.correlations[i]) > M_PI )
{
_eo.correlations[i] -= M_PI * (int) (_eo.correlations[i]/M_PI) ;
}
}
/*
* Perform correlated mutations.
*/
unsigned i,k;
vector<double> VarStp(_eo.size());
for (i = 0; i < _eo.size(); i++)
VarStp[i] = _eo.stdevs[i] * rng.normal();
unsigned nq = _eo.correlations.size() - 1;
for (k = 0; k < _eo.size()-1; k++)
{
n1 = _eo.size() - k - 1;
n2 = _eo.size() - 1;
for (i = 0; i < k; i++)
{
d1 = VarStp[n1];
d2 = VarStp[n2];
S = sin( _eo.correlations[nq] );
C = cos( _eo.correlations[nq] );
VarStp[n2] = d1 * S + d2 * C;
VarStp[n1] = d1 * C - d2 * S;
n2--;
nq--;
}
}
for (i = 0; i < _eo.size(); i++)
_eo[i] += VarStp[i];
keepInBounds(_eo);
}
void keepInBounds(EOT& _eo) const
{
for (unsigned i = 0; i < _eo.size(); ++i)
{
if (_eo[i] < bounds.minimum(i))
_eo[i] = bounds.minimum(i);
else if (_eo[i] > bounds.maximum(i))
_eo[i] = bounds.maximum(i);
}
}
private :
// the data
//=========
double TauLcl; /* Local factor for mutation of std deviations */
double TauGlb; /* Global factor for mutation of std deviations */
double TauBeta; /* Factor for mutation of correlation parameters */
eoESObjectiveBounds& bounds;
};
/*
* Correlated mutations in ESs, according to the following
* sources:
* H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80
* p. 43, 1980
* G. Rudolph: Globale Optimierung mit parallelen Evolutions-
* strategien, Diploma Thesis, University of Dortmund, 1990
*/
#endif

View file

@ -0,0 +1,62 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoEvalFuncPtrCnt.h
Same as eoEvalFuncPtr, but counts the number of evaluations
(c) GeNeura Team, 2000
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef EOEVALFUNCPTRCNT_H
#define EOEVALFUNCPTRCNT_H
#include <eoEvalFuncPtr.h>
/** EOEvalFuncCntPtr: This class
* takes an existing function pointer and converts it into a evaluation
* function class. That way, old style C or C++ functions can be adapted to EO
* function classes.
*/
template< class EOT >
struct eoEvalFuncPtrCnt: public eoEvalFuncPtr<EOT> {
/** Applies the function to the chromosome and sets the fitness of the
Chrom. Thus, the evaluation function need not be worried about that.
@param _eval pointer to the evaluation function, takes a EOT as an
argument and returns the fitness
@return the evaluated fitness for that object.
*/
eoEvalFuncPtrCnt( EOFitT (* _eval)( const EOT& ) )
: eoEvalFuncPtr<EOT>( _eval ), numOfEvaluations( 0 ) {};
/// Effectively applies the evaluation function to an EO
virtual void operator() ( EOT & _eo ) const {
eoEvalFuncPtr<EOT>::operator()( _eo );
numOfEvaluations++;
};
///
unsigned getNumOfEvaluations() const { return numOfEvaluations; };
private:
mutable unsigned numOfEvaluations;
};
#endif

View file

@ -0,0 +1,59 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoGenTerm.h
// (c) GeNeura Team, 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOFITTERM_H
#define _EOFITTERM_H
#include <eoContinue.h>
/**
Fitness continuation:
Continues until the maximum fitness level is reached.
*/
template< class EOT>
class eoFitContinue: public eoContinue<EOT> {
public:
/// Define Fitness
typedef typename EOT::Fitness FitnessType;
/// Ctor
eoFitContinue( const FitnessType _maximum)
: eoContinuator<EOT> (), maximum( _maximum ) {};
/** Returns false when a fitness criterium is
* reached, assumes sorted population */
virtual bool operator() ( const eoPop<EOT>& _vEO )
{
return (bestFitness < maximum);
}
private:
FitnessType maximum;
};
#endif

View file

@ -0,0 +1,57 @@
// eoFitness.h
//-----------------------------------------------------------------------------
// eoFitness.cpp
// (c) GeNeura Team 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef EOFITNESS_H
#define EOFITNESS_H
//-----------------------------------------------------------------------------
/**
\deprecated This class will dissapear in time, use eoScalarFitness instead
*/
class eoFitness: public eoPersistent
{
public:
virtual operator float() const = 0;
virtual bool operator<(const eoFitness& other) const = 0;
virtual bool operator>(const eoFitness& other) const
{
return !(*this < other || *this == other);
}
virtual bool operator==(const eoFitness& other) const
{
return !(other < *this || *this < other);
}
virtual bool operator!=(const eoFitness& other) const
{
return other < *this || *this < other;
}
};
//-----------------------------------------------------------------------------
#endif EOFITNESS_H

View file

@ -0,0 +1,68 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoGenTerm.h
// (c) GeNeura Team, 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOGENTERM_H
#define _EOGENTERM_H
#include <eoContinue.h>
/** Generational continuator: continues until a number of generations is reached
*/
template< class EOT>
class eoGenContinue: public eoContinue<EOT> {
public:
/// Ctors/dtors
eoGenContinue( unsigned _totalGens)
: repTotalGenerations( _totalGens ),
thisGeneration(0){};
/** Returns false when a certain number of generations is
* reached */
virtual bool operator() ( const eoPop<EOT>& _vEO ) {
thisGeneration++;
// cout << " [" << thisGeneration << "] ";
return (thisGeneration < repTotalGenerations) ; // for the postincrement
}
/** Sets the number of generations to reach
and sets the current generation to 0 (the begin)*/
virtual void totalGenerations( unsigned _tg ) {
repTotalGenerations = _tg;
// thisGeneration = 0;
};
/** Returns the number of generations to reach*/
virtual unsigned totalGenerations( ) {
return repTotalGenerations;
};
std::string className(void) const { return "eoGenTerm"; }
private:
unsigned repTotalGenerations, thisGeneration;
};
#endif

View file

@ -0,0 +1,85 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoOp.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef eoGeneration_h
#define eoGeneration_h
//-----------------------------------------------------------------------------
#include <eoAlgo.h> // eoPop
#include <eoEvalFunc.h>
#include <eoPopOps.h> // eoSelect, eoTranform, eoMerge
//-----------------------------------------------------------------------------
/** eoGeneration
* Single step of a evolutionary algorithm. Applies selection, then genetic
* operators, replaces using a replacement policy, and finally evaluates the
* new ones */
template<class Chrom> class eoGeneration: public eoAlgo<Chrom>
{
public:
/// Constructor.
eoGeneration(eoSelect<Chrom>& _select,
eoBreeder<Chrom>& _breeder,
eoBinPopOp<Chrom>& _replace,
eoEvalFunc<Chrom>& _evaluator):
select(_select), transform(_transform),
replace(_replace), evaluator( _evaluator) {};
/// Copy Constructor.
eoGeneration(eoGeneration<Chrom>& _gen):
select(_gen.select), transform(_gen.transform),
replace(_gen.replace), evaluator( _gen.evaluator ) {};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<Chrom>& pop) {
eoPop<Chrom> breeders;
try {
select(pop, breeders);
transform(breeders);
eoPop<Chrom>::iterator i;
// Can't use foreach here since foreach takes the
// parameter by reference
for ( i = breeders.begin(); i != breeders.end(); i++)
evaluator(*i);
replace(breeders, pop);
} catch ( exception& e ) {
throw runtime_error( e.what() );
}
}
/// Class name.
string className() const { return "eoGeneration"; }
private:
eoBinPopOp<Chrom>& select;
eoMonPopOp<Chrom>& transform;
eoBinPopOp<Chrom>& replace;
eoEvalFunc<Chrom>& evaluator;
};
//-----------------------------------------------------------------------------
#endif eoGeneration_h

110
eo/src/obsolete/eoID.h Normal file
View file

@ -0,0 +1,110 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoID.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#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

View file

@ -0,0 +1,64 @@
//-----------------------------------------------------------------------------
// eoInclusion.h
//-----------------------------------------------------------------------------
#ifndef eoInclusion_h
#define eoInclusion_h
//-----------------------------------------------------------------------------
#include <iostream>
// EO includes
#include <eoPop.h>
#include <eoMerge.h>
/*****************************************************************************
* eoInclusion: A replacement algorithm. *
* Creates a new population by selecting the best individuals from the *
* breeders and original populations *
*****************************************************************************/
template<class Chrom> class eoInclusion: public eoMerge<Chrom>
{
public:
/// (Default) Constructor.
eoInclusion(const float& _rate = 1.0): eoMerge<Chrom>( _rate ) {}
/// Ctor from istream
eoInclusion( istream& _is): eoBinPopOp<Chrom>( _is ) {};
/// Dtor
virtual ~eoInclusion() {};
/**
* Creates a new population based on breeders and original populations.
* @param breeders The population of breeders.
* @param pop The original population.
*/
void operator()(eoPop<Chrom>& breeders, eoPop<Chrom>& pop)
{
unsigned target = min(static_cast<unsigned>(pop.size() * rate()),
pop.size() + breeders.size());
copy(breeders.begin(), breeders.end(),
back_insert_iterator<eoPop<Chrom> >(pop));
partial_sort(pop.begin(), pop.begin() + target, pop.end(),
greater<Chrom>());
pop.erase(pop.begin() + target, pop.end());
}
/** @name Methods from eoObject */
//@{
/** readFrom and printOn inherited from eoMerge */
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
virtual string className() const {return "eoInclusion";};
//@}
};
//-----------------------------------------------------------------------------
#endif eoInclusion_h

View file

@ -0,0 +1,96 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoInsertion.h
// Inserts new members into the population
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef eoInsertion_h
#define eoInsertion_h
//-----------------------------------------------------------------------------
#include <iostream>
// EO includes
#include <eoPop.h> // eoPop
#include <eoMerge.h> // eoMerge
/******************************************************************************
* eoInsertion: A replacement algorithm.
* Creates a new population with all the breeders and the best individuals
* from the original population.
*****************************************************************************/
template<class Chrom> class eoInsertion: public eoBinaryFunctor<eoPop<Chrom>&, const eoPop<Chrom>&>
{
public:
/// (Default) Constructor.
eoInsertion(const float& _rate = 1.0): eoMerge<Chrom>( _rate ) {}
/// Ctor from istream
eoInsertion( istream& _is): eoBinPopOp<Chrom>( _is ) {};
/// Dtor
virtual ~eoInsertion() {};
/**
* Creates a new population based on breeders and original populations.
* @param breeders The population of breeders. Should be sorted to work correctly
* @param pop The original population.
*/
void operator()( eoPop<Chrom>& _breeders, const eoPop<Chrom>& _pop)
{
unsigned target = static_cast<unsigned>((_pop.size() * rate()));
_pop.swap(_breeders);
if (target < _pop.size())
{
partial_sort(_pop.begin(), _pop.begin() + target, _pop.end(),
greater<Chrom>());
_pop.erase(_pop.begin() + target, _pop.end());
}
else
{
target = min(target - _pop.size(), _breeders.size());
partial_sort(_breeders.begin(), _breeders.begin() + target,
_breeders.end(), greater<Chrom>());
copy(_breeders.begin(), _breeders.begin() + target,
back_insert_iterator<eoPop<Chrom> >(_pop));
}
};
/** @name Methods from eoObject */
//@{
/** readFrom and printOn inherited from eoMerge */
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
virtual string className() const {return "eoInsertion";};
//@}
};
//-----------------------------------------------------------------------------
#endif eoInsertion_h

62
eo/src/obsolete/eoKill.h Normal file
View file

@ -0,0 +1,62 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoKill.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOKILL_h
#define _EOKILL_h
#include <utils/eoRNG.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
{
unsigned pos = rng.random(_eo.length());
_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

105
eo/src/obsolete/eoLottery.h Normal file
View file

@ -0,0 +1,105 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoLottery.h
// Implements the lottery procedure for selection
// (c) GeNeura Team, 1998 - Marc Schoenauer, 2000
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef eoLottery_h
#define eoLottery_h
//-----------------------------------------------------------------------------
#include <stdexcept> // logic_error
#include <utils/selectors.h> // sum_fitness
#include <eoFunctor.h>
// #include <functional> //
// #include <numeric> // accumulate
// #include <eo> // eoPop eoSelect MINFLOAT
//-----------------------------------------------------------------------------
/** eoLottery: a selection method. Puts into the output a group of individuals
selected using lottery; individuals with higher probability will have more
chances of being selected.
Requires EOT::Fitness to be float castable
*/
//-----------------------------------------------------------------------------
template<class EOT> class eoLottery: public eoBinaryFunctor<void, const eoPop<EOT>&, eoPop<EOT>& >
{
public:
/// (Default) Constructor.
eoLottery(const float& _rate = 1.0): eoBinPopOp<EOT>(), rate_(_rate)
{
if (minimizing_fitness<EOT>())
{
throw logic_error("eoLottery: minimizing fitness");
}
}
/** actually selects individuals from pop and pushes them back them into breeders
* until breeders has the right size: rate*pop.size()
* BUT what happens if breeders is already too big?
* Too big for what?
*/
void operator()(const eoPop<EOT>& pop, eoPop<EOT>& breeders)
{
size_t target = static_cast<size_t>(rate_ * pop.size());
/* Gustavo: uncomment this if it must be here
// test of consistency
if (breeders.size() >= target) {
throw("Problem in eoLottery: already too many offspring");
}
double total;
try
{
total = sum_fitness (pop);
}
catch (eoNegativeFitnessException&)
{ // say where it occured...
throw eoNegativeFitnessException(*this);
}
*/
double total = sum_fitness (pop);
// selection of chromosomes
while (breeders.size() < target)
{
breeders.push_back(roulette_wheel(pop, total));
}
}
double rate(void) const { return rate_; }
private:
double rate_; // selection rate
};
//-----------------------------------------------------------------------------
#endif eoLottery_h

View file

@ -0,0 +1,90 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoMutation.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOMUTATION_H
#define _EOMUTATION_H
#include <math.h>
// EO includes
#include <eoOp.h>
/** Generic Mutation of an EO.
This is a virtual class, just to establish the interface for the ctor.
Mutation is usually type-specific
*/
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 {
typename EOT::iterator i;
for ( i = _eo.begin(); i != _eo.end(); 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 ;
};
#endif

View file

@ -0,0 +1,67 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoNegExp.h
(c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EONEGEXP_H
#define _EONEGEXP_H
//-----------------------------------------------------------------------------
#include <math.h>
#include <eoRnd.h> // for base class
#include <utils/eoRNG.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 Distribution 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 T( -mean*log((double)rng.rand() / rng.rand_max())); }
private:
T mean;
};
//-----------------------------------------------------------------------------
#endif

View file

@ -0,0 +1,87 @@
//-----------------------------------------------------------------------------
// eoNonUniform.h
//-----------------------------------------------------------------------------
#ifndef EONONUNIFORM_H
#define EONONUNIFORM_H
//-----------------------------------------------------------------------------
#include <math.h> // pow
//-----------------------------------------------------------------------------
// eoNonUniform
//-----------------------------------------------------------------------------
class eoNonUniform
{
public:
eoNonUniform(const unsigned _num_step):
step_value(0), num_step_value(_num_step) {}
void reset() { step_value = 0; }
const unsigned& step() const { return step_value; }
const unsigned& num_step() const { return num_step_value; }
operator int() const { return step_value < num_step_value; }
void operator++() { ++step_value; }
void operator++(int) { ++step_value; }
private:
unsigned step_value, num_step_value;
};
//-----------------------------------------------------------------------------
// eoLinear
//-----------------------------------------------------------------------------
class eoLinear
{
public:
eoLinear(const double _first,
const double _last,
const eoNonUniform& _non_uniform):
first(_first),
diff((_last - _first) / (_non_uniform.num_step() - 1)),
non_uniform(_non_uniform) {}
double operator()() const
{
return first + diff * non_uniform.step();
}
private:
double first, diff;
const eoNonUniform& non_uniform;
};
//-----------------------------------------------------------------------------
// eoNegExp2
//-----------------------------------------------------------------------------
class eoNegExp2
{
public:
eoNegExp2(const double _r,
const double _b,
const eoNonUniform& _non_uniform):
r(_r), b(_b),
non_uniform(_non_uniform) {}
double operator()() const
{
return 1.0 - pow(r, pow(1.0 - (double)non_uniform.step() /
non_uniform.num_step(), b));
}
private:
double r, b;
const eoNonUniform& non_uniform;
};
//-----------------------------------------------------------------------------
#endif NON_UNIFORM_HH

View file

@ -0,0 +1,89 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoNormal.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EONORMAL_H
#define _EONORMAL_H
//-----------------------------------------------------------------------------
#include <math.h>
#include <eoRnd.h> // for base class
#include <utils/eoRNG.h> // for random number generator
//-----------------------------------------------------------------------------
// 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)rng.rand() / rng.rand_max())*2-1;
q = ((double)rng.rand() / rng.rand_max())*2-1;
v = p*p + q*q;
} while(v > 1.0 || v <0.25);
sqRatio = sqrt(-2*log((double)rand() / rng.rand_max()) / v);
phase = true;
return T( (sqRatio * p * sd) + mean );
};
private:
T mean;
T sd;
bool phase;
double sqRatio, q;
};
//-----------------------------------------------------------------------------
#endif

142
eo/src/obsolete/eoPopOps.h Normal file
View file

@ -0,0 +1,142 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoPopOps.h
(c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOPOPOPS_H
#define _EOPOPOPS_H
using namespace std;
/**
@author Geneura Team
@version 0.0
@version 0.1 : -MS- 22/10/99
added the added the derived class eoSelectOne for which you only have
to define the selection of 1 individual
(e.g. for tournament, age selection in SSGA, ...)
added at the BASE level (after all it's themost frequen case)
the pure virtual operator that selects one single individual:
EOT eoSelect::operator ( const eoPop<EOT>& _parents,
const EOT& _first = 0)
added the optional second parameter to transform::operator()
*/
//-----------------------------------------------------------------------------
#include <eoPop.h>
//-----------------------------------------------------------------------------
/** eoTransform is a class that transforms or does something on a population.
*/
template<class EOT>
class eoMonPopOp: public eoObject{
public:
/** ctor */
eoMonPopOp() {};
/// Dtor
virtual ~eoMonPopOp(){};
/// 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
*/
virtual string className() const {return "eoMonPopOp";};
//@}
};
//-----------------------------------------------------------------------------
/** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */
template<class EOT>
class eoBinPopOp: public eoObject{
public:
/** ctor
*/
eoBinPopOp() {};
/// Dtor
virtual ~eoBinPopOp(){};
/** 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 () (eoPop<EOT>& _parents, eoPop<EOT>& _siblings ) = 0;
/** @name Methods from eoObject */
//@{
/** readFrom and printOn are not overriden
*/
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
virtual string className() const {return "eoBinPopOp";};
//@}
};
//-----------------------------------------------------------------------------
/** eoSelectone selects only one element from a whole population. Usually used to
select mates*/
template<class EOT>
class eoSelectOne: public eoObject{
public:
/** ctor
*/
eoSelectOne() {};
/// Dtor
virtual ~eoSelectOne(){};
/** 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 const EOT& operator () ( const eoPop<EOT>& _parents ) = 0;
/** @name Methods from eoObject */
//@{
/** readFrom and printOn are not overriden
*/
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
virtual string className() const {return "eoSelectOne";};
//@}
};
#endif

View file

@ -0,0 +1,200 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRandomBreed.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#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

View file

@ -0,0 +1,53 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoRandomIndiSelector.h
Selects individuals at random.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
#ifndef eoRandomIndiSelector_h
#define eoRandomIndiSelector_h
#include <eoIndiSelector.h>
/**
\ingroup selectors
* eoRandomSelector: just selects a random child
*/
template <class EOT>
class eoRandomIndiSelector : public eoPopIndiSelector<EOT>
{
public :
eoRandomIndiSelector(void) : eoPopIndiSelector<EOT>() {}
virtual ~eoRandomIndiSelector(void) {}
/// very complex function that returns just an individual
const EOT& do_select(void)
{
return operator[](rng.random(size()));
}
};
#endif

View file

@ -0,0 +1,130 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRandomSelect.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef EORANDOMSELECT_H
#define EORANDOMSELECT_H
//-----------------------------------------------------------------------------
#include <algorithm>
#include <numeric> // for accumulate
#include <functional>
#include <eoPopOps.h>
#include <utils/eoRNG.h>
//-----------------------------------------------------------------------------
/**
* eoRandomSelect: an selection operator, which selects randomly a percentage
of the initial population.
*/
template<class EOT> class eoRandomSelect: public eoBinPopOp<EOT>
{
public:
///
eoRandomSelect(const float& _percent = 0.4):
eoBinPopOp<EOT>(), repRate(_percent) {};
///
virtual ~eoRandomSelect() {};
/// Takes a percentage of the population randomly, and transfers it to siblings
virtual void operator() ( eoPop<EOT>& _parents, eoPop<EOT>& _siblings ) {
// generates random numbers
unsigned num_chroms = (unsigned)(repRate * _parents.size());
// selection of chromosomes
do {
_siblings.push_back(_parents[rng.random(_parents.size())]);
} 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 >> repRate;
}
/** 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 << repRate;
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoRandomSelect";};
//@}
private:
float repRate;
};
//-----------------------------------------------------------------------------
#endif EOGSRANDOMSELECT_H

140
eo/src/obsolete/eoRank.h Normal file
View file

@ -0,0 +1,140 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoRank.h
// (c) GeNeura Team 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#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 eoObject, public eoPrintable
{
public:
/// Ctor
eoRank( unsigned _newPopSize, eoOpSelector<EOT>& _opSelector)
:eoSelect<EOT>(), opSelector( _opSelector ), repNewPopSize( _newPopSize ) {};
/// 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
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[ rng.random(inLen) ];
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"; };
virtual void printOn( ostream& _s ) const
{
_s << repNewPopSize;
};
//@}
private:
eoOpSelector<EOT> & opSelector;
unsigned repNewPopSize;
};
#endif

61
eo/src/obsolete/eoRnd.h Normal file
View file

@ -0,0 +1,61 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoRnd.h
(c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#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. These 'numbers'
* can be anything, including full-fledged chromosomes.
*/
template<class T>
class eoRnd
{
public:
/** Main function: random generators act as functors, that return random numbers.
@return return a random number
*/
virtual T operator()() = 0;
};
#endif

360
eo/src/obsolete/eoScheme.h Normal file
View file

@ -0,0 +1,360 @@
// eoScheme.h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoScheme.h
// (c) GeNeura Team, 1998 - EEAAX 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOSCHEME_H
#define _EOSCHEME_H
using namespace std;
/**
@author Geneura Team -- EEAAX 99
@version 0.0
Evolution scheme
It seems to me that some important conceptual object is missing
(and God knows I hate turning everything into objects!
So here is the evolution scheme:
regroups selection (nb of offspring to generate AND selection method
and replacement (from parents + offspring)
allows to include elitism, eugenism of the worst, ... more easily
a generation is then simply an evolution scheme and some operators
and a full algo is a generation + a termination condition
this is mainly a container class
*/
//-----------------------------------------------------------------------------
#include <eoPopOps.h>
#include "eoStochTournament.h"
#include "eoDetTournament.h"
#include "eoLottery.h"
#include "eoUniformSelect.h"
#include "eoInclusion.h"
#include "eoESReplace.h"
#include "eoEPTournament.h"
/** eoScheme is a class that does more sophisticated evolution that eoEasyEA
*/
template<class EOT>
class eoScheme: public eoAlgo<EOT>{
public:
// Dtor
virtual ~eoScheme() {};
// copy ctor is impossible because of pointers to pure virual types.
// any idea???? --- leave the default copy ctor -- JJ
/** the Parser-based constructor
these switch cases could be turned into as many subclasses
- but how do you return the subclass to the caller of the constructor???
*/
eoScheme(Parser & parser) {
// read the popsize
parser.AddTitle("Description of evolution");
string Evol;
string SelectString;
// temporary
float rate_offspring;
try {
Evol = parser.getString("-EE", "--evolution", "GGA",
"Evolution scheme (GGA, SSGA, ESPlus, ESComma, EP, General)" );
popsize = parser.getInt("-EP", "--population", "10",
"Population size" );
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
// now the big switch
if (! strcasecmp(Evol.c_str(), "GGA") ) {
// GGA parameters: popsize, selection method (and its parameters)
nb_offspring = 0;
rate_offspring = 1.0; // generational replacement: #offspring=popsize
try {
// parser.AddTitle("GGA Parameters");
SelectString = parser.getString("-ES", "--selection", "Tournament",
"Selection method (Roulette, tournament)" );
if (! strcasecmp(SelectString.c_str(), "roulette") ) {
ptselect = new eoLottery<EOT> ();
ptselect_mate = new eoLottery<EOT> ();
}
if (! strcasecmp(SelectString.c_str(), "tournament") ) {
float rate = parser.getFloat("-Et", "--TselectSize", "2",
"Tournament size or rate" );
if (rate < 0.5)
throw out_of_range("Invalid tournament rate");
else if ( rate < 1 ) { // binary stochastic tournament
ptselect = new eoStochTournament<EOT>(rate);
ptselect_mate = new eoStochTournament<EOT>(rate);
} else { // determeinistic tournament of size (int)rate
ptselect = new eoDetTournament<EOT>((int)rate);
ptselect_mate = new eoDetTournament<EOT>((int)rate);
}
}
// end choice of selection
ptreplace = new eoInclusion<EOT>();
// put here the choice of elitism
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
} // end of GGA
// SSGA - standard, one offspring only at the moment
if (! strcasecmp(Evol.c_str(), "SSGA") ) {
// SSGA parameters: popsize, selection tournament size
// the replacement is limited to repace_worst, though
// it could be easy to add the anti-tournament replacement method
nb_offspring = 1;
// NOTE: of course it's a bit of a waste to use the standard loop
// for one single offspring ...
try {
// parser.AddTitle("SSGA Parameters");
float _rate = parser.getFloat("-ET", "--TSelectSize", "2",
"Selection tournament size" );
if ( _rate < 1 ) { // binary stochastic tournament
ptselect = new eoStochTournament<EOT>(_rate);
ptselect_mate = new eoStochTournament<EOT>(_rate);
} else { // determeinistic tournament of size (int)rate
ptselect = new eoDetTournament<EOT>((int)_rate);
ptselect_mate = new eoDetTournament<EOT>((int)_rate);
}
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
// end choice of selection
ptreplace = new eoInclusion<EOT>();
// put here the choice of elitism
} // end of SSGA
if (! strcasecmp(Evol.c_str(), "ESPlus") ) {
// ES evolution parameters: lambda = _nb_offspring
try {
// parser.AddTitle("ES Scheme parameters");
nb_offspring = parser.getInt("-EL", "--lambda", "50",
"Lambda" );
ptselect = new eoUniformSelect<EOT>();
ptselect_mate = new eoUniformSelect<EOT>();
ptreplace = new eoESPlus<EOT>();
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
} // end of ESPlus
if (! strcasecmp(Evol.c_str(), "ESComma") ) {
// ES evolution parameters: lambda = _nb_offspring
try {
// parser.AddTitle("ES Scheme parameters");
nb_offspring = parser.getInt("-EL", "--lambda", "50",
"Lambda" );
ptselect = new eoUniformSelect<EOT>();
ptselect_mate = new eoUniformSelect<EOT>();
ptreplace = new eoESComma<EOT>();
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
} // end of ESCOmma
if (! strcasecmp(Evol.c_str(), "EP") ) {
// EP evoltion scheme: only the EP-tournament replacement size is neede
try {
// parser.AddTitle("EP Scheme parameters");
nb_offspring = popsize;
ptselect = new eoCopySelect<EOT>; /* no selection */
ptselect_mate = new eoUniformSelect<EOT>();
/* What, crossover in EP :-) */
unsigned tsize = parser.getInt("-ET", "--TournamentSize", "6",
"Size of stocahstic replacement tournament" );
ptreplace = new eoEPTournament<EOT>(tsize);
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
} // end of EP
// everyting is read: now the consistency checks and other preliminary steps
nb_offspring = (nb_offspring ? nb_offspring :
(int) (rate_offspring * popsize) );
if (!nb_offspring)
nb_offspring = 1; /* al least one offspring */
}
// accessors
unsigned PopSize(){return popsize;}
unsigned NbOffspring(){return nb_offspring ;}
eoSelect<EOT>* PtSelect(){return ptselect;}
eoSelect<EOT>* PtSelectMate(){return ptselect_mate;}
eoMerge<EOT>* PtMerge() {return ptreplace;}
// NOTE: need pointers otherwise you have many warnings when initializing
/** @name Methods from eoObject */
//@{
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
string className() const {return "eoScheme";};
//@}
private:
unsigned popsize; /* but should it be here ??? */
unsigned nb_offspring; /* to generate through selection+operators */
// these are provisional for later use
// float rate_offspring; /* or rate */
// unsigned nb_survive; /* the best guys that are transmitted anyway */
// float rate_survive; /* or rate */
// unsigned nb_die; /* the worst guys that do not enev enter selection */
// float rate_die; /* or rate */
eoSelect<EOT> * ptselect;
eoSelect<EOT>* ptselect_mate;
eoMerge<EOT>* ptreplace;
bool elitism; /* put back old best in the new population if necessary */
};
/* examples:
for most populat schemes, nb_survive = nb_die = 0
in GGA and EP, nb_offspring = pop.size()
in ES, nb_offspring = lambda
in SSGA, nb_offspring = 1 (usually)
elitism can be used anywhere - though stupid in ES, EP and SSGA who are
elist by definition
*/
#endif _EOSCHEME_H
/*
/////////////////////////////////
/// Applies one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop) {
// Determine the number of offspring to create
// either prescribed, or given as a rate
unsigned nb_off_local = (nb_offspring ? nb_offspring :
(int) rint (rate_offspring * pop.size()) );
nb_off_local = (nb_off_local ? nb_off_local : 1); // in case it is rounded to 0!
// the worst die immediately
unsigned nb_die_local = (nb_die ? nb_die :
(int) rint (rate_die * pop.size()) );
// and the best will survive without selection
unsigned nb_survive_local = (nb_survive ? nb_survive :
(int) rint (rate_survive * pop.size()) );
// before selection, erase the one to die
// sort old pop - just in case!
sort(pop.begin(), pop.end(), greater<EOT>());
Fitness oldBest = pop[0].fitness(); // store for elitism
eoPop<EOT> fertilepop = pop;
if (nb_die_local)
erase(fertilepop.end()-nb_die_local, fertilepop.end());
eoPop<EOT> offspring; // = select(fertilepop, nb_off_local);
select(fertilepop, offspring, nb_off_local);
// now apply the operators to offspring
for (unsigned i=0; i<nb_local; i++) {
EOT tmp = offspring[i];
unsigned id = 0; // first operator
eoOp<EOT>* op = seqselop.Op(&id);
while (op) { // NULL if no more operator
EOT mate;
if (op->readArity() == binary) // can eventually be skipped
mate = select_mate(pop, tmp); // though useless ig mutation
else
mate = tmp; // assumed: mate will not be used!
cout << op->className() << " for offspring " << i << endl;
tmp = (*op)( tmp, mate, pop );
op = seqselop.Op(&id);
}
offspring[i]=tmp; //* where it belongs
}
eoPop<EOT>::iterator i;
// Can't use foreach here since foreach takes the
// parameter by reference
for ( i = offspring.begin(); i != offspring.end(); i++)
evaluator(*i);
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// not exact - later!!!
// -MS-
// first, copy the ones that need to survive
// assumed: pop is still sorted!
eoPop<EOT> finalPop;
// and the best survive without selection
if (nb_survive_local) {
finalPop.resize(nb_survive_local);
copy( finalPop.begin(), fertilepop.begin(),
fertilepop.begin()+nb_survive_local );
}
// now call the replacement method
replace(finalPop, tmpPop);
// handle elitlism
sort(finalPop.begin(), finalPop.end(), greater<EOT>());
if (elitism) {
if ( finalPop[0].fitness() < oldBest ) // best fitness has decreased!
copy(finalPop.end()-1, pop[0]);
}
// return finalPop;
}
*/

View file

@ -0,0 +1,77 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoStringMutation.h
// (c) GeNeura Team, 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOSTRINGMUTATION_H
#define _EOSRTINGMUTATION_H
#include <math.h>
// EO includes
#include <eoOp.h>
#include <utils/eoRNG.h>
#include <eoMutation.h>
/** 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 {
if( rate < uniform() ) {
_eo.gene(_i) += ( rng.flip(0.5))? (1) : (-1) ;
}
}
};
//-----------------------------------------------------------------------------
#endif

56
eo/src/obsolete/eoTerm.h Normal file
View file

@ -0,0 +1,56 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoTerm.h
// (c) GeNeura Team, 1999, 2000
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOTERM_H
#define _EOTERM_H
//#include <eoPop.h>
// forward definition for fast(er) compilation
template <class EOT> class eoPop;
/** Termination condition for the genetic algorithm
* Takes the population as input, returns true for continue,
* false for termination (although this begs the question why this
* terminator is not called a continuator)
*
*/
template< class EOT>
class eoTerm : public eoObject {
public:
/// Ctors/dtors
virtual ~eoTerm() {};
/** Returns false if the training has to stop, true if it
continues \\
It is non-const since it might change the internal state
of the object, for instance, updating local data.
*/
virtual bool operator() ( const eoPop< EOT >& _pop ) = 0 ;
};
#endif

View file

@ -0,0 +1,157 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoTournament.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOGSTOURN_H
#define _EOGSTOURN_H
//-----------------------------------------------------------------------------
#include <utils/eoRNG.h>
#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 eoBinPopOp<EOT>{
public:
/// Proportion of guys that are going to be eliminated
eoTournament( float _perc, unsigned _tSize):
eoBinPopOp<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() ( eoPop<EOT>& _vEO, eoPop<EOT>& _aVEO) {
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;
for ( unsigned k = 0; k < repTournamentSize; k++ ) {
unsigned chosen = rng.random(thisSize);
EOT newEO = _vEO[chosen];
veoTournament.push_back( newEO );
}
eoPop<EOT>::const_iterator best = max_element(veoTournament.begin(),
veoTournament.end());
if (best == veoTournament.end()) {
throw runtime_error("error in void eoTournament::operator(eoPop<EOT>&, eoPop<EOT>&)");
}
// The best individual is chosen for the new population
_aVEO.push_back( *best );
}
};
/// @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

View file

@ -0,0 +1,94 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoTranspose.h
// (c) GeNeura Team, 1998 Maarten Keijzer 2000
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOTRANSPOSE_h
#define _EOTRANSPOSE_h
#include <vector>
#include <list>
#include <utils/eoRNG.h>
#include <eoOp.h>
#include <eoFixedLength.h>
#include <eoVariableLength.h>
/**
Transposition operator: interchanges the position of two genes
of an EO.
*/
template <class EOT >
class eoTranspose: public eoMonOp<EOT>
{
public:
// Specialization for a vector
void operator()(eoFixedLength<typename EOT::Fitness, typename EOT::AtomType>& _eo )
{
unsigned pos1 = rng.random(_eo.size()),
pos2 = rng.random(_eo.size());
if (pos1 != pos2)
swap(_eo[pos1], _eo[pos2]);
if (_eo[pos1] != _eo[pos2])
_eo.invalidate();
}
// Specialization for a list
void operator()(eoVariableLength<typename EOT::Fitness, typename EOT::AtomType>& _eo )
{
unsigned pos1 = rng.random(_eo.size()),
pos2 = rng.random(_eo.size());
if (pos1 == pos2)
return;
if (pos1 > pos2)
swap(pos1,pos2);
pos2 -= pos1;
typename EOT::iterator it1 = _eo.begin();
while (pos1--) {it1++;}
typename EOT::iterator it2 = it1;
while (pos2--) {it2++;}
swap(*it1, *it2);
if (*it1 != *it2)
_eo.invalidate();
}
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoTranspose";};
//@}
};
#endif

View file

@ -0,0 +1,94 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoUniform.h
Uniform random number generator;
(c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOUNIFORM_H
#define _EOUNIFORM_H
//-----------------------------------------------------------------------------
#include <eoRnd.h>
#include <utils/eoRNG.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>(), min(_min), diff(_max - _min) {}
/**
* copy constructor.
* @param _rnd the other rnd
*/
eoUniform( const eoUniform& _rnd)
: eoRnd<T>( _rnd), min(_rnd.min), diff(_rnd.diff) {}
/** Returns an uniform random number over the interval [min, max)
Uses global rng object */
virtual T operator()() {
return min + T( rng.uniform( diff ) );
}
private:
T min;
double diff;
};
template<>
class eoUniform<bool>: public eoRnd<bool>
{
public:
/**
* Default constructor.
* @param _min The minimum value in the interval.
* @param _max The maximum value in the interval.
*/
eoUniform(bool _min = false, bool _max = true)
: eoRnd<bool>() {}
/** Returns an uniform random number over the interval [min, max)
Uses global rng object */
virtual bool operator()() {
return rng.flip(0.5);
}
private:
bool min;
double diff;
};
//-----------------------------------------------------------------------------
#endif

View file

@ -0,0 +1,176 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoUniformXOver.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOUNIFORMXOVER_h
#define _EOUNIFORMXOVER_h
// for swap
#if defined( __BORLANDC__ )
#include <algorith>
#else
#include <algorithm>
#endif
// EO includes
#include <eoOp.h>
#include <utils/eoRNG.h>
//-----------------------------------------------------------------------------
/**
* EOUniformCrossover: operator for binary chromosomes
* implementation of uniform crossover for EO
* swaps ranges of bits between the parents
*/
//-----------------------------------------------------------------------------
template<class EOT>
class eoUniformXOver: public eoQuadraticOp< EOT >
{
public:
///
eoUniformXOver( float _rate = 0.5 ):
eoQuadraticOp< EOT > ( ), rate( _rate ) {
if (rate < 0 || rate > 1)
runtime_error("UxOver --> invalid rate");
}
///
void operator() ( EOT& chrom1, EOT& chrom2 ) const {
unsigned end = min(chrom1.length(),chrom2.length()) - 1;
// select bits to change
// aply changes
for (unsigned bit = 0; bit < end; bit++)
if (rng.flip(rate))
swap(chrom1[ bit], chrom2[ bit]);
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoUniformXOver";};
//@}
private:
float rate; /// rate of uniform crossover
};
//-----------------------------------------------------------------------------
#endif

170
eo/src/obsolete/eoVector.h Normal file
View file

@ -0,0 +1,170 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoVector.h
Turns an STL vector into an EO
(c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#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=float>
class eoVector: public eo1d<T, fitnessT>, public vector<T> {
public:
typedef T Type ;
/// 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 = 0, 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 getGene( 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 void setGene( unsigned _i, const T& _value ) {
if ( _i >= size() )
throw out_of_range( "out_of_range when writing a gene");
(*this)[_i] = _value;
};
/** 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

107
eo/src/obsolete/eoXOver2.h Normal file
View file

@ -0,0 +1,107 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoXOver2.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOXOVER2_h
#define _EOXOVER2_h
// for swap
#if defined( __BORLANDC__ )
#include <algorith>
#else
#include <algorithm>
#endif
// EO includes
#include <eoOp.h>
#include <utils/eoRNG.h>
/** 2-point crossover: takes the genes in the central section of two EOs
and interchanges it
*/
template <class EOT>
class eoXOver2: public eoQuadraticOp<EOT> {
public:
///
eoXOver2()
: eoQuadraticOp< EOT >(){};
///
virtual ~eoXOver2() {};
///
virtual void operator()( EOT& _eo1,
EOT& _eo2 ) const {
unsigned len1 = _eo1.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1;
unsigned pos1 = rng.random(len), pos2 = rng.random(len) ;
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