Changed double linefeeds, will undo this if it doesn't work

This commit is contained in:
mac 2000-02-19 18:21:47 +00:00
commit 0d439f9f56
62 changed files with 7612 additions and 7555 deletions

View file

@ -1,238 +1,238 @@
#ifndef EO_PARSE_TREE_H
#define EO_PARSE_TREE_H
#include <list>
#include "EO.h"
#include "eoOp.h"
#include "eoInserter.h"
#include "eoIndiSelector.h"
#include "parse_tree.h"
#include "eoRnd.h"
using namespace gp_parse_tree;
using namespace std;
template <class FType, class Node>
class eoParseTree : public EO<FType>, public parse_tree<Node>
{
public :
typedef typename parse_tree<Node>::subtree Type;
eoParseTree(void) : EO<FType>(), parse_tree<Node>() {}
eoParseTree(unsigned _size, eoRnd<Type>& _rnd)
: EO<FType>(), parse_tree<Node>(_rnd())
{
pruneTree(_size);
}
void pruneTree(unsigned _size)
{
if (_size < 1)
return;
if (size() > _size)
{
Type* sub = &operator[](size() - 2); // prune tree
while (sub->size() > _size)
{
sub = &sub->operator[](0);
}
back() = *sub;
}
}
eoParseTree(std::istream& is) : EO<FType>(), parse_tree<Node>()
{
readFrom(is);
}
string className(void) const { return "eoParseTree"; }
void printOn(std::ostream& os) const
{
os << fitness() << ' ';
std::copy(ebegin(), eend(), ostream_iterator<Node>(os));
}
void readFrom(std::istream& is)
{
FType fit;
is >> fit;
fitness(fit);
std::copy(istream_iterator<Node>(is), istream_iterator<Node>(), back_inserter(*this));
}
};
template <class FType, class Node>
std::ostream& operator<<(std::ostream& os, const eoParseTree<FType, Node>& eot)
{
eot.printOn(os);
return os;
}
template <class FType, class Node>
std::istream& operator>>(std::istream& is, eoParseTree<FType, Node>& eot)
{
eot.readFrom(is);
return is;
}
template <class FType, class Node>
class eoGpDepthInitializer : public eoRnd< eoParseTree<FType, Node>::Type >
{
public :
typedef eoParseTree<FType, Node> EoType;
eoGpDepthInitializer(
unsigned _max_depth,
const vector<Node>& _initializor,
bool _grow = true)
:
eoRnd<EoType::Type>(),
max_depth(_max_depth),
initializor(_initializor),
grow(_grow)
{}
virtual string className() const { return "eoDepthInitializer"; };
EoType::Type operator()(void)
{
list<Node> sequence;
generate(sequence, max_depth);
parse_tree<Node> tree(sequence.begin(), sequence.end());
return tree.root();
}
void generate(list<Node>& sequence, int the_max, int last_terminal = -1)
{
if (last_terminal == -1)
{ // check where the last terminal in the sequence resides
vector<Node>::iterator it;
for (it = initializor.begin(); it != initializor.end(); ++it)
{
if (it->arity() > 1)
break;
}
last_terminal = it - initializor.begin();
}
if (the_max == 1)
{ // generate terminals only
vector<Node>::iterator it = initializor.begin() + rng.random(last_terminal);
sequence.push_front(*it);
return;
}
vector<Node>::iterator what_it;
if (grow)
{
what_it = initializor.begin() + rng.random(initializor.size());
}
else // full
{
what_it = initializor.begin() + last_terminal + rng.random(initializor.size() - last_terminal);
}
sequence.push_front(*what_it);
for (int i = 0; i < what_it->arity(); ++i)
generate(sequence, the_max - 1, last_terminal);
}
private :
unsigned max_depth;
std::vector<Node> initializor;
bool grow;
};
template<class FType, class Node>
class eoSubtreeXOver: public eoGeneralOp< eoParseTree<FType, Node> > {
public:
typedef eoParseTree<FType, Node> EoType;
eoSubtreeXOver( unsigned _max_length)
: eoGeneralOp<EoType>(), max_length(_max_length) {};
virtual string className() const { return "eoSubtreeXOver"; };
/// Dtor
virtual ~eoSubtreeXOver () {};
void operator()(eoIndiSelector<EoType>& _source, eoInserter<EoType>& _sink ) const
{
EoType eo1 = _source.select();
const EoType& eo2 = _source.select();
int i = rng.random(eo1.size());
int j = rng.random(eo2.size());
eo1[i] = eo2[j]; // insert subtree
eo1.pruneTree(max_length);
eo1.invalidate();
_sink.insert(eo1);
}
unsigned max_length;
};
template<class FType, class Node>
class eoBranchMutation: public eoGeneralOp< eoParseTree<FType, Node> >
{
public:
typedef eoParseTree<FType, Node> EoType;
eoBranchMutation(eoRnd<EoType::Type>& _init, unsigned _max_length)
: eoGeneralOp<EoType>(), max_length(_max_length), initializer(_init)
{};
virtual string className() const { return "eoBranchMutation"; };
/// Dtor
virtual ~eoBranchMutation() {};
void operator()(eoIndiSelector<EoType>& _source, eoInserter<EoType>& _sink ) const
{
EoType eo1 = _source.select();
int i = rng.random(eo1.size());
EoType eo2(eo1[i].size(), initializer); // create random other to cross with
eo1[i] = eo2.back(); // insert subtree
eo1.pruneTree(max_length);
eo1.invalidate();
_sink.insert(eo1);
}
private :
unsigned max_length;
eoRnd<EoType::Type>& initializer;
};
#endif
#ifndef EO_PARSE_TREE_H
#define EO_PARSE_TREE_H
#include <list>
#include "EO.h"
#include "eoOp.h"
#include "eoInserter.h"
#include "eoIndiSelector.h"
#include "parse_tree.h"
#include "eoRnd.h"
using namespace gp_parse_tree;
using namespace std;
template <class FType, class Node>
class eoParseTree : public EO<FType>, public parse_tree<Node>
{
public :
typedef typename parse_tree<Node>::subtree Type;
eoParseTree(void) : EO<FType>(), parse_tree<Node>() {}
eoParseTree(unsigned _size, eoRnd<Type>& _rnd)
: EO<FType>(), parse_tree<Node>(_rnd())
{
pruneTree(_size);
}
void pruneTree(unsigned _size)
{
if (_size < 1)
return;
if (size() > _size)
{
Type* sub = &operator[](size() - 2); // prune tree
while (sub->size() > _size)
{
sub = &sub->operator[](0);
}
back() = *sub;
}
}
eoParseTree(std::istream& is) : EO<FType>(), parse_tree<Node>()
{
readFrom(is);
}
string className(void) const { return "eoParseTree"; }
void printOn(std::ostream& os) const
{
os << fitness() << ' ';
std::copy(ebegin(), eend(), ostream_iterator<Node>(os));
}
void readFrom(std::istream& is)
{
FType fit;
is >> fit;
fitness(fit);
std::copy(istream_iterator<Node>(is), istream_iterator<Node>(), back_inserter(*this));
}
};
template <class FType, class Node>
std::ostream& operator<<(std::ostream& os, const eoParseTree<FType, Node>& eot)
{
eot.printOn(os);
return os;
}
template <class FType, class Node>
std::istream& operator>>(std::istream& is, eoParseTree<FType, Node>& eot)
{
eot.readFrom(is);
return is;
}
template <class FType, class Node>
class eoGpDepthInitializer : public eoRnd< eoParseTree<FType, Node>::Type >
{
public :
typedef eoParseTree<FType, Node> EoType;
eoGpDepthInitializer(
unsigned _max_depth,
const vector<Node>& _initializor,
bool _grow = true)
:
eoRnd<EoType::Type>(),
max_depth(_max_depth),
initializor(_initializor),
grow(_grow)
{}
virtual string className() const { return "eoDepthInitializer"; };
EoType::Type operator()(void)
{
list<Node> sequence;
generate(sequence, max_depth);
parse_tree<Node> tree(sequence.begin(), sequence.end());
return tree.root();
}
void generate(list<Node>& sequence, int the_max, int last_terminal = -1)
{
if (last_terminal == -1)
{ // check where the last terminal in the sequence resides
vector<Node>::iterator it;
for (it = initializor.begin(); it != initializor.end(); ++it)
{
if (it->arity() > 1)
break;
}
last_terminal = it - initializor.begin();
}
if (the_max == 1)
{ // generate terminals only
vector<Node>::iterator it = initializor.begin() + rng.random(last_terminal);
sequence.push_front(*it);
return;
}
vector<Node>::iterator what_it;
if (grow)
{
what_it = initializor.begin() + rng.random(initializor.size());
}
else // full
{
what_it = initializor.begin() + last_terminal + rng.random(initializor.size() - last_terminal);
}
sequence.push_front(*what_it);
for (int i = 0; i < what_it->arity(); ++i)
generate(sequence, the_max - 1, last_terminal);
}
private :
unsigned max_depth;
std::vector<Node> initializor;
bool grow;
};
template<class FType, class Node>
class eoSubtreeXOver: public eoGeneralOp< eoParseTree<FType, Node> > {
public:
typedef eoParseTree<FType, Node> EoType;
eoSubtreeXOver( unsigned _max_length)
: eoGeneralOp<EoType>(), max_length(_max_length) {};
virtual string className() const { return "eoSubtreeXOver"; };
/// Dtor
virtual ~eoSubtreeXOver () {};
void operator()(eoIndiSelector<EoType>& _source, eoInserter<EoType>& _sink ) const
{
EoType eo1 = _source.select();
const EoType& eo2 = _source.select();
int i = rng.random(eo1.size());
int j = rng.random(eo2.size());
eo1[i] = eo2[j]; // insert subtree
eo1.pruneTree(max_length);
eo1.invalidate();
_sink.insert(eo1);
}
unsigned max_length;
};
template<class FType, class Node>
class eoBranchMutation: public eoGeneralOp< eoParseTree<FType, Node> >
{
public:
typedef eoParseTree<FType, Node> EoType;
eoBranchMutation(eoRnd<EoType::Type>& _init, unsigned _max_length)
: eoGeneralOp<EoType>(), max_length(_max_length), initializer(_init)
{};
virtual string className() const { return "eoBranchMutation"; };
/// Dtor
virtual ~eoBranchMutation() {};
void operator()(eoIndiSelector<EoType>& _source, eoInserter<EoType>& _sink ) const
{
EoType eo1 = _source.select();
int i = rng.random(eo1.size());
EoType eo2(eo1[i].size(), initializer); // create random other to cross with
eo1[i] = eo2.back(); // insert subtree
eo1.pruneTree(max_length);
eo1.invalidate();
_sink.insert(eo1);
}
private :
unsigned max_length;
eoRnd<EoType::Type>& initializer;
};
#endif

View file

@ -1,228 +1,228 @@
#ifndef node_pool_h
#define node_pool_h
class MemPool
{
public :
MemPool(unsigned int sz) : esize(sz<sizeof(Link)? sizeof(Link) : sz) {}
~MemPool()
{
Chunk* n = chunks;
while(n)
{
Chunk* p = n;
n = n->next;
delete p;
}
}
void* allocate()
{
if (head == 0) grow();
Link* p = head;
head = p->next;
return static_cast<void*>(p);
}
void deallocate(void* b)
{
Link* p = static_cast<Link*>(b);
p->next = head;
head = p;
}
private :
void grow()
{
Chunk* n = new Chunk;
n->next = chunks;
chunks = n;
const int nelem = Chunk::size/esize;
char* start = n->mem;
char* last = &start[(nelem-1)*esize];
for (char* p = start; p < last; p += esize)
{
reinterpret_cast<Link*>(p)->next =
reinterpret_cast<Link*>(p + esize);
}
reinterpret_cast<Link*>(last)->next = 0;
head = reinterpret_cast<Link*>(start);
}
struct Link
{
Link* next;
};
struct Chunk
{
enum {size = 8 * 1024 - 16};
Chunk* next;
char mem[size];
};
Chunk* chunks;
const unsigned int esize;
Link* head;
};
template<class T>
class Node_alloc
{
public :
Node_alloc() {};
T* allocate(void)
{
T* t = static_cast<T*>(mem.allocate());
t = new (t) T;
//t->T(); // call constructor;
return t;
}
void deallocate(T* t)
{
t->~T(); // call destructor
mem.deallocate(static_cast<void*>(t));
}
private :
static MemPool mem;
};
template <class T>
class Standard_alloc
{
public :
Standard_alloc() {}
T* allocate(size_t arity = 1)
{
if (arity == 0)
return 0;
return new T [arity];
}
void deallocate(T* t, size_t arity = 1)
{
if (arity == 0)
return ;
delete [] t;
}
};
template <class T>
class Standard_Node_alloc
{
public :
Standard_Node_alloc() {}
T* allocate(void)
{
return new T;// [arity];
}
void deallocate(T* t)
{
delete t;
}
};
template <class T>
class Tree_alloc
{
public :
Tree_alloc() {}
T* allocate(size_t arity)
{
T* t;
switch(arity)
{
case 0 : return 0;
case 1 :
{
t = static_cast<T*>(mem1.allocate());
new (t) T;
break;
}
case 2 :
{
t = static_cast<T*>(mem2.allocate());
new (t) T;
new (&t[1]) T;
break;
}
case 3 :
{
t = static_cast<T*>(mem3.allocate());
new (t) T;
new (&t[1]) T;
new (&t[2]) T;
break;
}
default :
{
return new T[arity];
}
}
return t;
}
void deallocate(T* t, size_t arity)
{
switch(arity)
{
case 0: return;
case 3 :
{
t[2].~T(); t[1].~T(); t[0].~T();
mem3.deallocate(static_cast<void*>(t));
return;
}
case 2 :
{
t[1].~T(); t[0].~T();
mem2.deallocate(static_cast<void*>(t));
return;
}
case 1 :
{
t[0].~T();
mem1.deallocate(static_cast<void*>(t));
return;
}
default :
{
delete [] t;
return;
}
}
}
private :
static MemPool mem1;
static MemPool mem2;
static MemPool mem3;
};
// static (non thread_safe) memory pools
template <class T> MemPool Node_alloc<T>::mem = sizeof(T);
template <class T> MemPool Tree_alloc<T>::mem1 = sizeof(T);
template <class T> MemPool Tree_alloc<T>::mem2 = sizeof(T) * 2;
template <class T> MemPool Tree_alloc<T>::mem3 = sizeof(T) * 3;
#endif
#ifndef node_pool_h
#define node_pool_h
class MemPool
{
public :
MemPool(unsigned int sz) : esize(sz<sizeof(Link)? sizeof(Link) : sz) {}
~MemPool()
{
Chunk* n = chunks;
while(n)
{
Chunk* p = n;
n = n->next;
delete p;
}
}
void* allocate()
{
if (head == 0) grow();
Link* p = head;
head = p->next;
return static_cast<void*>(p);
}
void deallocate(void* b)
{
Link* p = static_cast<Link*>(b);
p->next = head;
head = p;
}
private :
void grow()
{
Chunk* n = new Chunk;
n->next = chunks;
chunks = n;
const int nelem = Chunk::size/esize;
char* start = n->mem;
char* last = &start[(nelem-1)*esize];
for (char* p = start; p < last; p += esize)
{
reinterpret_cast<Link*>(p)->next =
reinterpret_cast<Link*>(p + esize);
}
reinterpret_cast<Link*>(last)->next = 0;
head = reinterpret_cast<Link*>(start);
}
struct Link
{
Link* next;
};
struct Chunk
{
enum {size = 8 * 1024 - 16};
Chunk* next;
char mem[size];
};
Chunk* chunks;
const unsigned int esize;
Link* head;
};
template<class T>
class Node_alloc
{
public :
Node_alloc() {};
T* allocate(void)
{
T* t = static_cast<T*>(mem.allocate());
t = new (t) T;
//t->T(); // call constructor;
return t;
}
void deallocate(T* t)
{
t->~T(); // call destructor
mem.deallocate(static_cast<void*>(t));
}
private :
static MemPool mem;
};
template <class T>
class Standard_alloc
{
public :
Standard_alloc() {}
T* allocate(size_t arity = 1)
{
if (arity == 0)
return 0;
return new T [arity];
}
void deallocate(T* t, size_t arity = 1)
{
if (arity == 0)
return ;
delete [] t;
}
};
template <class T>
class Standard_Node_alloc
{
public :
Standard_Node_alloc() {}
T* allocate(void)
{
return new T;// [arity];
}
void deallocate(T* t)
{
delete t;
}
};
template <class T>
class Tree_alloc
{
public :
Tree_alloc() {}
T* allocate(size_t arity)
{
T* t;
switch(arity)
{
case 0 : return 0;
case 1 :
{
t = static_cast<T*>(mem1.allocate());
new (t) T;
break;
}
case 2 :
{
t = static_cast<T*>(mem2.allocate());
new (t) T;
new (&t[1]) T;
break;
}
case 3 :
{
t = static_cast<T*>(mem3.allocate());
new (t) T;
new (&t[1]) T;
new (&t[2]) T;
break;
}
default :
{
return new T[arity];
}
}
return t;
}
void deallocate(T* t, size_t arity)
{
switch(arity)
{
case 0: return;
case 3 :
{
t[2].~T(); t[1].~T(); t[0].~T();
mem3.deallocate(static_cast<void*>(t));
return;
}
case 2 :
{
t[1].~T(); t[0].~T();
mem2.deallocate(static_cast<void*>(t));
return;
}
case 1 :
{
t[0].~T();
mem1.deallocate(static_cast<void*>(t));
return;
}
default :
{
delete [] t;
return;
}
}
}
private :
static MemPool mem1;
static MemPool mem2;
static MemPool mem3;
};
// static (non thread_safe) memory pools
template <class T> MemPool Node_alloc<T>::mem = sizeof(T);
template <class T> MemPool Tree_alloc<T>::mem1 = sizeof(T);
template <class T> MemPool Tree_alloc<T>::mem2 = sizeof(T) * 2;
template <class T> MemPool Tree_alloc<T>::mem3 = sizeof(T) * 3;
#endif

File diff suppressed because it is too large Load diff

View file

@ -1,76 +1,76 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
compatibility.h
File to store some compiler specific stuff in. Currently handles, or
least tries to handle the min() max() problems when using MSVC
(c) Maarten Keijzer (mak@dhi.dk) 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 COMPAT_H
#define COMPAT_H
#include <string>
#include <iostream>
#ifdef _1__GNUC__
// Specifics for GNUC
#define NO_GOOD_ISTREAM_ITERATORS
#endif
#ifdef _MSC_VER
/*
Maarten: added this code here because Mirkosoft has the
nasty habit of #define min and max in stdlib.h (and windows.h)
I'm trying to undo this horrible macro magic (microsoft yet macrohard)
here. Sure hope it works
*/
#include <stdlib.h>
#ifdef min
#undef min
#undef max // as they come in pairs
#endif
// add min and max to std...
namespace std
{
template <class T> T min(const T& a, const T& b)
{
if(a < b)
return a;
// else
return b;
}
template <class T> T max(const T& a, const T& b)
{
if(a > b)
return a;
// else
return b;
}
}
#endif // _MSC_VER
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
compatibility.h
File to store some compiler specific stuff in. Currently handles, or
least tries to handle the min() max() problems when using MSVC
(c) Maarten Keijzer (mak@dhi.dk) 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 COMPAT_H
#define COMPAT_H
#include <string>
#include <iostream>
#ifdef _1__GNUC__
// Specifics for GNUC
#define NO_GOOD_ISTREAM_ITERATORS
#endif
#ifdef _MSC_VER
/*
Maarten: added this code here because Mirkosoft has the
nasty habit of #define min and max in stdlib.h (and windows.h)
I'm trying to undo this horrible macro magic (microsoft yet macrohard)
here. Sure hope it works
*/
#include <stdlib.h>
#ifdef min
#undef min
#undef max // as they come in pairs
#endif
// add min and max to std...
namespace std
{
template <class T> T min(const T& a, const T& b)
{
if(a < b)
return a;
// else
return b;
}
template <class T> T max(const T& a, const T& b)
{
if(a > b)
return a;
// else
return b;
}
}
#endif // _MSC_VER
#endif

View file

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

View file

@ -1,65 +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 <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
// -*- 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 <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

@ -1,95 +1,96 @@
// -*- 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 <eoUniform.h>
#include <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 tipe
*/
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
// -*- 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 <eoUniform.h>
#include <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 tipe
*/
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

@ -1,61 +1,62 @@
// -*- 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
/** 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.
*/
template <class T>
class eoAtomMutator: public eoPrintable {
public:
///
eoAtomMutator() {};
///
virtual ~eoAtomMutator() {};
///
virtual void operator()( T& _val ) const = 0;
/** @name Methods from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
///
virtual string className() const {return "eoAtomMutator";};
///
void printOn(ostream& _os) const { _os << className() << endl; };
//@}
};
#endif
// -*- 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
/** 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.
*/
template <class T>
class eoAtomMutator: public eoPrintable {
public:
///
eoAtomMutator() {};
///
virtual ~eoAtomMutator() {};
///
virtual void operator()( T& _val ) const = 0;
/** @name Methods from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
///
virtual string className() const {return "eoAtomMutator";};
///
void printOn(ostream& _os) const { _os << className() << endl; };
//@}
};
#endif

View file

@ -1,54 +1,54 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoInserter.h
Abstract population insertion operator, which is used by the eoGeneralOps
to insert the results in the (intermediate) population. This file also
contains the definitions of a derived classes that implements a back inserter,
probably the only efficient inserter for populations of type vector.
(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 eoBackInserter_h
#define eoBackInserter_h
#include "eoInserter.h"
/**
* eoBackInserter: Interface class that enables an operator to insert
new individuals at the back of the new population.
*/
template <class EOT>
class eoBackInserter : public eoPopInserter<EOT>
{
public :
eoBackInserter(void) : eoPopInserter<EOT>() {}
void insert(const EOT& _eot)
{
pop().push_back(_eot);
}
string className(void) const { return "eoBackInserter"; }
};
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoInserter.h
Abstract population insertion operator, which is used by the eoGeneralOps
to insert the results in the (intermediate) population. This file also
contains the definitions of a derived classes that implements a back inserter,
probably the only efficient inserter for populations of type vector.
(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 eoBackInserter_h
#define eoBackInserter_h
#include "eoInserter.h"
/**
* eoBackInserter: Interface class that enables an operator to insert
new individuals at the back of the new population.
*/
template <class EOT>
class eoBackInserter : public eoPopInserter<EOT>
{
public :
eoBackInserter(void) : eoPopInserter<EOT>() {}
void insert(const EOT& _eot)
{
pop().push_back(_eot);
}
string className(void) const { return "eoBackInserter"; }
};
#endif

View file

@ -1,324 +1,325 @@
//-----------------------------------------------------------------------------
// eoBitOp.h
//-----------------------------------------------------------------------------
#ifndef eoBitOp_h
#define eoBitOp_h
//-----------------------------------------------------------------------------
#include <algorithm> // swap_ranges
#include <eoUniform.h> // eoUniform
#include <eoBin.h> // eoBin
#include <eoOp.h> // eoMonOp
/** @name BitWise Genetic operators
Even as these operators might seem general, they are particular versions of genetic
operators useful only for binary operators. As any set of genetic operators, it must
have a factory that knows how to build them from a description
@author GeNeura Team
@version 0.1
@see eoBin
@see eoBitOpFactory
*/
//@{
/** eoBinRandom --> mofify a chromosome in a random way */
template<class Chrom> class eoBinRandom: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinRandom"; }
/**
* Randomizes a cromosome.
* @param chrom The cromosome to be randomize.
*/
void operator()(Chrom& chrom) const
{
eoUniform<float> uniform(0.0, 1.0);
for (unsigned i = 0; i < chrom.size(); i++)
chrom[i] = (uniform() < 0.5) ? false : true;
}
};
/** eoBinBitFlip --> chages a bit */
template<class Chrom> class eoBinBitFlip: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinBitFlip"; }
/**
* Change one bit.
* @param chrom The cromosome which one bit is going to be changed.
*/
void operator()(Chrom& chrom) const
{
eoUniform<int> uniform(0, chrom.size());
unsigned i = uniform();
chrom[i] = (chrom[i]) ? false : true;
}
};
/** eoBinMutation --> classical mutation */
template<class Chrom> class eoBinMutation: public eoMonOp<Chrom>
{
public:
/**
* (Default) Constructor.
* @param _rate Rate of mutation.
*/
eoBinMutation(const double& _rate = 0.01): rate(_rate), uniform(0.0, 1.0) {}
/// The class name.
string className() const { return "eoBinMutation"; }
/**
* Mutate a chromosome.
* @param chrom The chromosome to be mutated.
*/
void operator()(Chrom& chrom) const
{
for (unsigned i = 0; i < chrom.size(); i++)
if (uniform() < rate)
chrom[i] = !chrom[i];
}
private:
double rate;
mutable eoUniform<float> uniform;
};
/** eoBinInversion: inverts the bits of the chromosome between an interval */
template<class Chrom> class eoBinInversion: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinInversion"; }
/**
* Inverts a range of bits in a binary chromosome.
* @param chrom The chromosome whos bits are going to be inverted (a range).
*/
void operator()(Chrom& chrom) const
{
eoUniform<unsigned> uniform(0, chrom.size() + 1);
unsigned u1 = uniform(), u2;
do u2 = uniform(); while (u1 == u2);
unsigned r1 = min(u1, u2), r2 = max(u1, u2);
reverse(chrom.begin() + r1, chrom.begin() + r2);
}
};
/** eoBinNext --> next binary value */
template<class Chrom> class eoBinNext: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinNext"; }
/**
* Change the bit string x to be x+1.
* @param chrom The chromosome to be added one.
*/
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
continue;
}
else
{
chrom[i] = 1;
break;
}
}
};
/** eoBinPrev --> previos binary value */
template<class Chrom> class eoBinPrev: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinPrev"; }
/**
* Change the bit string x to be x-1.
* @param chrom The chromosome to be substracted one.
*/
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
break;
}
else
{
chrom[i] = 1;
continue;
}
}
};
/** eoBinCrossover --> classic crossover */
template<class Chrom> class eoBinCrossover: public eoQuadraticOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinCrossover"; }
/**
* 2-point crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
eoUniform<unsigned> uniform(1, min(chrom1.size(), chrom2.size()));
swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin());
}
};
/** eoBinNxOver --> n-point crossover */
template<class Chrom> class eoBinNxOver: public eoQuadraticOp<Chrom>
{
public:
/// (Defualt) Constructor.
eoBinNxOver(const unsigned& _num_points = 2): num_points(_num_points)
{
if (num_points < 1)
runtime_error("NxOver --> invalid number of points");
}
/// The class name.
string className() const { return "eoBinNxOver"; }
/**
* n-point crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_size = min(chrom1.size(), chrom2.size());
unsigned max_points = min(max_size - 1, num_points);
vector<bool> points(max_size, false);
eoUniform<unsigned> uniform(1, max_size);
// select ranges of bits to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
max_points--;
}
} while (max_points);
// swap bits between chromosomes
bool change = false;
for (unsigned bit = 1; bit < points.size(); bit++)
{
if (points[bit])
change = !change;
if (change)
swap(chrom1[bit], chrom2[bit]);
}
}
private:
unsigned num_points;
};
/** eoBinGxOver --> gene crossover */
template<class Chrom> class eoBinGxOver: public eoQuadraticOp<Chrom>
{
public:
/// Constructor.
eoBinGxOver(const unsigned _gene_size, const unsigned _num_points = 2):
gene_size(_gene_size), num_points(_num_points)
{
if (gene_size < 1)
runtime_error("GxOver --> invalid gene size");
if (num_points < 1)
runtime_error("GxOver --> invalid number of points");
}
/// The class name
string className() const { return "eoBinGxOver"; }
/**
* Gene crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_genes = min(chrom1.size(), chrom2.size()) / gene_size;
unsigned cut_genes = min(max_genes, num_points);
vector<bool> points(max_genes, false);
eoUniform<unsigned> uniform(0, max_genes);
// selects genes to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
cut_genes--;
}
} while (cut_genes);
// swaps genes
for (unsigned i = 0; i < points.size(); i++)
if (points[i])
swap_ranges(chrom1.begin() + i * gene_size,
chrom1.begin() + i * gene_size + gene_size,
chrom2.begin() + i * gene_size);
}
private:
unsigned gene_size;
unsigned num_points;
};
//-----------------------------------------------------------------------------
//@}
#endif eoBitOp_h
//-----------------------------------------------------------------------------
// eoBitOp.h
//-----------------------------------------------------------------------------
#ifndef eoBitOp_h
#define eoBitOp_h
//-----------------------------------------------------------------------------
#include <algorithm> // swap_ranges
#include <eoUniform.h> // eoUniform
#include <eoBin.h> // eoBin
#include <eoOp.h> // eoMonOp
/** @name BitWise Genetic operators
Even as these operators might seem general, they are particular versions of genetic
operators useful only for binary operators. As any set of genetic operators, it must
have a factory that knows how to build them from a description
@author GeNeura Team
@version 0.1
@see eoBin
@see eoBitOpFactory
*/
//@{
/** eoBinRandom --> mofify a chromosome in a random way */
template<class Chrom> class eoBinRandom: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinRandom"; }
/**
* Randomizes a cromosome.
* @param chrom The cromosome to be randomize.
*/
void operator()(Chrom& chrom) const
{
eoUniform<float> uniform(0.0, 1.0);
for (unsigned i = 0; i < chrom.size(); i++)
chrom[i] = (uniform() < 0.5) ? false : true;
}
};
/** eoBinBitFlip --> chages a bit */
template<class Chrom> class eoBinBitFlip: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinBitFlip"; }
/**
* Change one bit.
* @param chrom The cromosome which one bit is going to be changed.
*/
void operator()(Chrom& chrom) const
{
eoUniform<int> uniform(0, chrom.size());
unsigned i = uniform();
chrom[i] = (chrom[i]) ? false : true;
}
};
/** eoBinMutation --> classical mutation */
template<class Chrom> class eoBinMutation: public eoMonOp<Chrom>
{
public:
/**
* (Default) Constructor.
* @param _rate Rate of mutation.
*/
eoBinMutation(const double& _rate = 0.01): rate(_rate), uniform(0.0, 1.0) {}
/// The class name.
string className() const { return "eoBinMutation"; }
/**
* Mutate a chromosome.
* @param chrom The chromosome to be mutated.
*/
void operator()(Chrom& chrom) const
{
for (unsigned i = 0; i < chrom.size(); i++)
if (uniform() < rate)
chrom[i] = !chrom[i];
}
private:
double rate;
mutable eoUniform<float> uniform;
};
/** eoBinInversion: inverts the bits of the chromosome between an interval */
template<class Chrom> class eoBinInversion: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinInversion"; }
/**
* Inverts a range of bits in a binary chromosome.
* @param chrom The chromosome whos bits are going to be inverted (a range).
*/
void operator()(Chrom& chrom) const
{
eoUniform<unsigned> uniform(0, chrom.size() + 1);
unsigned u1 = uniform(), u2;
do u2 = uniform(); while (u1 == u2);
unsigned r1 = min(u1, u2), r2 = max(u1, u2);
reverse(chrom.begin() + r1, chrom.begin() + r2);
}
};
/** eoBinNext --> next binary value */
template<class Chrom> class eoBinNext: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinNext"; }
/**
* Change the bit string x to be x+1.
* @param chrom The chromosome to be added one.
*/
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
continue;
}
else
{
chrom[i] = 1;
break;
}
}
};
/** eoBinPrev --> previos binary value */
template<class Chrom> class eoBinPrev: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinPrev"; }
/**
* Change the bit string x to be x-1.
* @param chrom The chromosome to be substracted one.
*/
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
break;
}
else
{
chrom[i] = 1;
continue;
}
}
};
/** eoBinCrossover --> classic crossover */
template<class Chrom> class eoBinCrossover: public eoQuadraticOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinCrossover"; }
/**
* 2-point crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
eoUniform<unsigned> uniform(1, min(chrom1.size(), chrom2.size()));
swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin());
}
};
/** eoBinNxOver --> n-point crossover */
template<class Chrom> class eoBinNxOver: public eoQuadraticOp<Chrom>
{
public:
/// (Defualt) Constructor.
eoBinNxOver(const unsigned& _num_points = 2): num_points(_num_points)
{
if (num_points < 1)
runtime_error("NxOver --> invalid number of points");
}
/// The class name.
string className() const { return "eoBinNxOver"; }
/**
* n-point crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_size = min(chrom1.size(), chrom2.size());
unsigned max_points = min(max_size - 1, num_points);
vector<bool> points(max_size, false);
eoUniform<unsigned> uniform(1, max_size);
// select ranges of bits to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
max_points--;
}
} while (max_points);
// swap bits between chromosomes
bool change = false;
for (unsigned bit = 1; bit < points.size(); bit++)
{
if (points[bit])
change = !change;
if (change)
swap(chrom1[bit], chrom2[bit]);
}
}
private:
unsigned num_points;
};
/** eoBinGxOver --> gene crossover */
template<class Chrom> class eoBinGxOver: public eoQuadraticOp<Chrom>
{
public:
/// Constructor.
eoBinGxOver(const unsigned _gene_size, const unsigned _num_points = 2):
gene_size(_gene_size), num_points(_num_points)
{
if (gene_size < 1)
runtime_error("GxOver --> invalid gene size");
if (num_points < 1)
runtime_error("GxOver --> invalid number of points");
}
/// The class name
string className() const { return "eoBinGxOver"; }
/**
* Gene crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_genes = min(chrom1.size(), chrom2.size()) / gene_size;
unsigned cut_genes = min(max_genes, num_points);
vector<bool> points(max_genes, false);
eoUniform<unsigned> uniform(0, max_genes);
// selects genes to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
cut_genes--;
}
} while (cut_genes);
// swaps genes
for (unsigned i = 0; i < points.size(); i++)
if (points[i])
swap_ranges(chrom1.begin() + i * gene_size,
chrom1.begin() + i * gene_size + gene_size,
chrom2.begin() + i * gene_size);
}
private:
unsigned gene_size;
unsigned num_points;
};
//-----------------------------------------------------------------------------
//@}
#endif eoBitOp_h

View file

@ -1,119 +1,120 @@
// eoBitOpFactory.h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoOpFactory.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 _EOBITOPFACTORY_H
#define _EOBITOPFACTORY_H
#include <eoOpFactory.h>
#include <eoBitOp.h>
//-----------------------------------------------------------------------------
/** EO Factory. An instance of the factory class to create operators that act
on bitstring chromosomes. Only those chromosomes can instantiate the operators
that are created here
@see eoSelect*/
template< class EOT>
class eoBitOpFactory: public eoOpFactory<EOT> {
public:
/// @name ctors and dtors
//{@
/// constructor
eoBitOpFactory( ) {};
/// destructor
virtual ~eoBitOpFactory() {};
//@}
/** Another factory method: creates an object from an istream, reading from
it whatever is needed to create the object. Usually, the format for the istream will be\\
objectType parameter1 parameter2 ... parametern\\
If there are problems, an exception is raised; it should be caught at the
upper level, because it might be something for that level\\
At the same time, it catches exceptions thrown at a lower level, which will
indicate that whatever is in the stream is for this method to process
@param _is an stream from where a single line will be read
@throw runtime_exception if the object type is not known
*/
virtual eoOp<EOT>* make(istream& _is) {
eoOp<EOT> * opPtr = NULL;
try {
opPtr = eoOpFactory<EOT>::make( _is );
} catch ( const string& objectTypeStr ) {
if ( objectTypeStr == "eoBinRandom") {
opPtr = new eoBinRandom<EOT>();
}
if ( objectTypeStr == "eoBinBitFlip" ) {
opPtr = new eoBinBitFlip<EOT>( );
}
if ( objectTypeStr == "eoBinMutation" ) {
float rate;
_is >> rate;
opPtr = new eoBinMutation<EOT>( rate );
}
if ( objectTypeStr == "eoBinInversion" ) {
opPtr = new eoBinInversion<EOT>( );
}
if ( objectTypeStr == "eoBinNext" ) {
opPtr = new eoBinNext<EOT>( );
}
if ( objectTypeStr == "eoBinPrev" ) {
opPtr = new eoBinPrev<EOT>( );
}
if ( objectTypeStr == "eoBinNext" ) {
opPtr = new eoBinNext<EOT>( );
}
if ( objectTypeStr == "eoBinCrossover" ) {
opPtr = new eoBinCrossover<EOT>( );
}
if ( objectTypeStr == "eoBinNxOver" ) {
unsigned nPoints;
_is >> nPoints;
opPtr = new eoBinNxOver<EOT>( nPoints );
}
if ( objectTypeStr == "eoBinGxOver" ) {
unsigned geneSize, nPoints;
_is >> geneSize >> nPoints;
opPtr = new eoBinGxOver<EOT>( geneSize, nPoints );
}
if ( objectTypeStr == "eoBinUxOver" ) {
float rate;
_is >> rate;
opPtr = new eoBinUxOver<EOT>( rate );
}
if ( !opPtr ) { // to be caught by the upper level
throw objectTypeStr;
}
}
return opPtr;
};
};
#endif _EOBITOPFACTORY_H
// eoBitOpFactory.h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoOpFactory.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 _EOBITOPFACTORY_H
#define _EOBITOPFACTORY_H
#include <eoOpFactory.h>
#include <eoBitOp.h>
//-----------------------------------------------------------------------------
/** EO Factory. An instance of the factory class to create operators that act
on bitstring chromosomes. Only those chromosomes can instantiate the operators
that are created here
@see eoSelect*/
template< class EOT>
class eoBitOpFactory: public eoOpFactory<EOT> {
public:
/// @name ctors and dtors
//{@
/// constructor
eoBitOpFactory( ) {};
/// destructor
virtual ~eoBitOpFactory() {};
//@}
/** Another factory method: creates an object from an istream, reading from
it whatever is needed to create the object. Usually, the format for the istream will be\\
objectType parameter1 parameter2 ... parametern\\
If there are problems, an exception is raised; it should be caught at the
upper level, because it might be something for that level\\
At the same time, it catches exceptions thrown at a lower level, which will
indicate that whatever is in the stream is for this method to process
@param _is an stream from where a single line will be read
@throw runtime_exception if the object type is not known
*/
virtual eoOp<EOT>* make(istream& _is) {
eoOp<EOT> * opPtr = NULL;
try {
opPtr = eoOpFactory<EOT>::make( _is );
} catch ( const string& objectTypeStr ) {
if ( objectTypeStr == "eoBinRandom") {
opPtr = new eoBinRandom<EOT>();
}
if ( objectTypeStr == "eoBinBitFlip" ) {
opPtr = new eoBinBitFlip<EOT>( );
}
if ( objectTypeStr == "eoBinMutation" ) {
float rate;
_is >> rate;
opPtr = new eoBinMutation<EOT>( rate );
}
if ( objectTypeStr == "eoBinInversion" ) {
opPtr = new eoBinInversion<EOT>( );
}
if ( objectTypeStr == "eoBinNext" ) {
opPtr = new eoBinNext<EOT>( );
}
if ( objectTypeStr == "eoBinPrev" ) {
opPtr = new eoBinPrev<EOT>( );
}
if ( objectTypeStr == "eoBinNext" ) {
opPtr = new eoBinNext<EOT>( );
}
if ( objectTypeStr == "eoBinCrossover" ) {
opPtr = new eoBinCrossover<EOT>( );
}
if ( objectTypeStr == "eoBinNxOver" ) {
unsigned nPoints;
_is >> nPoints;
opPtr = new eoBinNxOver<EOT>( nPoints );
}
if ( objectTypeStr == "eoBinGxOver" ) {
unsigned geneSize, nPoints;
_is >> geneSize >> nPoints;
opPtr = new eoBinGxOver<EOT>( geneSize, nPoints );
}
if ( objectTypeStr == "eoBinUxOver" ) {
float rate;
_is >> rate;
opPtr = new eoBinUxOver<EOT>( rate );
}
if ( !opPtr ) { // to be caught by the upper level
throw objectTypeStr;
}
}
return opPtr;
};
};
#endif _EOBITOPFACTORY_H

View file

@ -1,113 +1,114 @@
// -*- 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 <eoUniform.h> // eoUniform
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include <eoPop.h> // eoPop
#include <eoPopOps.h> // eoTransform
#include <eoOpSelector.h> // eoOpSelector
#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 eoMonPopOp<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);
eoUniform<unsigned> u(0, pop.size() );
(*binop)(pop[i], pop[ u() ] );
break;
}
case eoOp<Chrom>::quadratic:
{
eoQuadraticOp<Chrom>* Qop = static_cast<eoQuadraticOp<Chrom>* >(op);
eoUniform<unsigned> u(0, pop.size() );
(*Qop)(pop[i], pop[ u() ] );
break;
}
case eoOp<Chrom>::general :
{
eoGeneralOp<Chrom>* Gop = static_cast<eoGeneralOp<Chrom>* >(op);
eoRandomIndiSelector<Chrom> selector;
eoBackInserter<Chrom> inserter;
(*Gop)(selector(pop, orgsize, i), inserter(pop));
break;
}
}
}
};
/// The class name.
string classname() const { return "eoBreeder"; }
private:
eoOpSelector<Chrom>& opSel;
};
//-----------------------------------------------------------------------------
#endif eoBreeder_h
// -*- 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 <eoUniform.h> // eoUniform
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include <eoPop.h> // eoPop
#include <eoPopOps.h> // eoTransform
#include <eoOpSelector.h> // eoOpSelector
#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 eoMonPopOp<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);
eoUniform<unsigned> u(0, pop.size() );
(*binop)(pop[i], pop[ u() ] );
break;
}
case eoOp<Chrom>::quadratic:
{
eoQuadraticOp<Chrom>* Qop = static_cast<eoQuadraticOp<Chrom>* >(op);
eoUniform<unsigned> u(0, pop.size() );
(*Qop)(pop[i], pop[ u() ] );
break;
}
case eoOp<Chrom>::general :
{
eoGeneralOp<Chrom>* Gop = static_cast<eoGeneralOp<Chrom>* >(op);
eoRandomIndiSelector<Chrom> selector;
eoBackInserter<Chrom> inserter;
(*Gop)(selector(pop, orgsize, i), inserter(pop));
break;
}
}
}
};
/// The class name.
string classname() const { return "eoBreeder"; }
private:
eoOpSelector<Chrom>& opSel;
};
//-----------------------------------------------------------------------------
#endif eoBreeder_h

View file

@ -1,65 +1,64 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoData.h
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoData.h
Some numeric limits and types and things like that; with #ifdefs to keep
compatibility
(c) GeNeura Team & Maarten Keijzer, 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 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 EODATA_H
#define EODATA_H
//-----------------------------------------------------------------------------
#include <vector> // vector
#include <set> // set
#include <string> // string
using namespace std;
#ifdef _MSC_VER
#include <limits> // MAXDOUBLE
#define MAXFLOAT numeric_limits<float>::max()
#define MINFLOAT numeric_limits<float>::min()
#define MAXDOUBLE numeric_limits<double>::max()
#define MAXINT numeric_limits<int>::max()
#else
#include <float.h>
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 EODATA_H
#define EODATA_H
//-----------------------------------------------------------------------------
#include <vector> // vector
#include <set> // set
#include <string> // string
using namespace std;
#ifdef _MSC_VER
#include <limits> // MAXDOUBLE
#define MAXFLOAT numeric_limits<float>::max()
#define MINFLOAT numeric_limits<float>::min()
#define MAXDOUBLE numeric_limits<double>::max()
#define MAXINT numeric_limits<int>::max()
#else
#include <float.h>
#include <limits.h>
#ifndef _WIN32 // should be the define for UN*X flavours: _POSIX??
#include <values.h>
#include <values.h>
#endif
#ifndef MAXFLOAT
#define MAXFLOAT (float)1e127
#define MAXDOUBLE (double)1.79769313486231570e+308
#define MAXINT 2147483647
#endif
#endif
#ifndef _MSC_VER
#include <math.h>
#define _isnan isnan
#endif
//-----------------------------------------------------------------------------
#endif EODATA_H
#ifndef MAXFLOAT
#define MAXFLOAT (float)1e127
#define MAXDOUBLE (double)1.79769313486231570e+308
#define MAXINT 2147483647
#endif
#endif
#ifndef _MSC_VER
#include <math.h>
#define _isnan isnan
#endif
//-----------------------------------------------------------------------------
#endif EODATA_H

View file

@ -1,70 +1,71 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoDetTournament.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 eoDetTournament_h
#define eoDetTournament_h
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include "selectors.h"
//-----------------------------------------------------------------------------
/** eoDetTournament: a selection method that selects ONE individual by
deterministic tournament
-MS- 24/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoDetTournament: public eoSelectOne<EOT>
{
public:
/// (Default) Constructor.
eoDetTournament(unsigned _Tsize = 2 ):eoSelectOne<EOT>(), Tsize(_Tsize) {
// consistency check
if (Tsize < 2) {
cout << "Warning, Tournament size should be >= 2\nAdjusted\n";
Tsize = 2;
}
}
virtual const EOT& operator()(const eoPop<EOT>& pop)
{
return deterministic_tournament(pop, Tsize)();
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoDetTournament";};
private:
unsigned Tsize;
};
//-----------------------------------------------------------------------------
#endif eoDetTournament_h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoDetTournament.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 eoDetTournament_h
#define eoDetTournament_h
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include "selectors.h"
//-----------------------------------------------------------------------------
/** eoDetTournament: a selection method that selects ONE individual by
deterministic tournament
-MS- 24/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoDetTournament: public eoSelectOne<EOT>
{
public:
/// (Default) Constructor.
eoDetTournament(unsigned _Tsize = 2 ):eoSelectOne<EOT>(), Tsize(_Tsize) {
// consistency check
if (Tsize < 2) {
cout << "Warning, Tournament size should be >= 2\nAdjusted\n";
Tsize = 2;
}
}
virtual const EOT& operator()(const eoPop<EOT>& pop)
{
return deterministic_tournament(pop, Tsize)();
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoDetTournament";};
private:
unsigned Tsize;
};
//-----------------------------------------------------------------------------
#endif eoDetTournament_h

View file

@ -1,57 +1,57 @@
/* -*- 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 "selectors.h"
/**
* 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
/* -*- 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 "selectors.h"
/**
* 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

@ -1,69 +1,69 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoDetTournamentInserter.h
Concrete steady state inserter. It is initialized with a population and
inserts individuals in the population based on an inverse deterministic
tournament
(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 eoDetTournamentInserter_h
#define eoDetTournamentInserter_h
#include "eoSteadyStateInserter.h"
#include "selectors.h"
/**
* eoDetTournamentInserter: Uses an inverse deterministic tournament to figure
* out who gets overridden by the new individual. It resets the fitness of the
* individual.
*/
template <class EOT>
class eoDetTournamentInserter : public eoSteadyStateInserter<EOT>
{
public :
eoDetTournamentInserter(eoEvalFunc<EOT>& _eval, unsigned _t_size) : t_size(_t_size), eoSteadyStateInserter<EOT>(_eval)
{
if (t_size < 2)
{ // warning, error?
t_size = 2;
}
}
void insert(const EOT& _eot)
{
EOT& eo = inverse_deterministic_tournament<EOT>(pop(), t_size);
eo = _eot; // overwrite loser of tournament
eo.invalidate(); // This line should probably be removed when all genetic operators do this themselves
eval(eo); // Evaluate after insert
}
string className(void) const { return "eoDetTournamentInserter"; }
private :
unsigned t_size;
};
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoDetTournamentInserter.h
Concrete steady state inserter. It is initialized with a population and
inserts individuals in the population based on an inverse deterministic
tournament
(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 eoDetTournamentInserter_h
#define eoDetTournamentInserter_h
#include "eoSteadyStateInserter.h"
#include "selectors.h"
/**
* eoDetTournamentInserter: Uses an inverse deterministic tournament to figure
* out who gets overridden by the new individual. It resets the fitness of the
* individual.
*/
template <class EOT>
class eoDetTournamentInserter : public eoSteadyStateInserter<EOT>
{
public :
eoDetTournamentInserter(eoEvalFunc<EOT>& _eval, unsigned _t_size) : t_size(_t_size), eoSteadyStateInserter<EOT>(_eval)
{
if (t_size < 2)
{ // warning, error?
t_size = 2;
}
}
void insert(const EOT& _eot)
{
EOT& eo = inverse_deterministic_tournament<EOT>(pop(), t_size);
eo = _eot; // overwrite loser of tournament
eo.invalidate(); // This line should probably be removed when all genetic operators do this themselves
eval(eo); // Evaluate after insert
}
string className(void) const { return "eoDetTournamentInserter"; }
private :
unsigned t_size;
};
#endif

View file

@ -1,63 +1,64 @@
// 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 <eoUniform.h>
#include <eoOp.h>
/// Dup or duplicate: duplicates a gene in a chromosome
template <class EOT>
class eoDup: public eoMonOp<EOT> {
public:
///
eoDup( )
: eoMonOp< EOT >( ){};
/// needed virtual dtor
virtual ~eoDup() {};
///
virtual void operator()( EOT& _eo ) const {
eoUniform<unsigned> uniform( 0, _eo.length() );
unsigned pos = uniform();
_eo.insertGene( pos, _eo.gene(pos) );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoDup";};
//@}
};
#endif
// 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 <eoUniform.h>
#include <eoOp.h>
/// Dup or duplicate: duplicates a gene in a chromosome
template <class EOT>
class eoDup: public eoMonOp<EOT> {
public:
///
eoDup( )
: eoMonOp< EOT >( ){};
/// needed virtual dtor
virtual ~eoDup() {};
///
virtual void operator()( EOT& _eo ) const {
eoUniform<unsigned> uniform( 0, _eo.length() );
unsigned pos = uniform();
_eo.insertGene( pos, _eo.gene(pos) );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoDup";};
//@}
};
#endif

View file

@ -1,125 +1,126 @@
// -*- 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
*/
//@{
/** Each gene in an Evolution Strategies is composed of a value plus an standard
deviation, sigma, used for mutation*/
struct eoESGene {
double val, sigma;
eoESGene( double _val = 0, double _sigma = 0 ): val( _val ), sigma( _sigma ) {};
};
/// Tricky operator to avoid errors in some VC++ systems, namely VC 5.0 SP3
bool operator < ( eoESGene _e1, eoESGene _e2 ) {
return _e1.val < _e2.val;
}
/// Tricky operator to avoid errors in some VC++ systems
bool operator == ( eoESGene _e1, eoESGene _e2 ) {
return ( _e1.val == _e2.val ) && ( _e1.sigma == _e2.sigma ) ;
}
///
ostream & operator << ( ostream& _s, const eoESGene& _e ) {
_s << _e.val << ", " << _e.sigma << " | ";
return _s;
}
/// Dummy >>
istream & operator >> ( istream& _s, const eoESGene& _e ) {
_s >> _e.val;
_s >> _e.sigma;
return _s;
}
/** Basic chromosome for evolution strategies (ES), as defined by Rechenberg and
Schwefel. Each chromosomes is composed of "genes"; each one of then is an eoESGene
@see eoESGene
*/
template <typename fitT = float >
class eoESChrom: public eoVector<eoESGene, fitT> {
public:
/// Basic ctor
eoESChrom( ):eoVector<eoESGene, fitT>() {};
/** Ctor using a couple of random number generators
@param _size Lineal length of the object
@param _rnd a random number generator, which returns a random value each time it´s called.
@param _rndS another one, for the sigma
*/
eoESChrom( unsigned _size, eoRnd<double>& _rnd, eoRnd<double>& _rndS )
: eoVector<eoESGene, fitT>( _size ){
for ( iterator i = begin(); i != end(); i ++ ) {
i->val = _rnd();
i->sigma = _rndS();
}
};
/// Copy ctor
eoESChrom( const eoESChrom& _eoes): eoVector<eoESGene, fitT>( _eoes ) {};
/// Assignment operator
const eoESChrom& operator =( const eoESChrom & _eoes ) {
if ( this != &_eoes ){
eoVector<eoESGene, fitT>::operator=( _eoes );
}
return *this;
}
///
~eoESChrom() {};
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoESChrom";};
//@}
};
//@}
#endif
// -*- 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
*/
//@{
/** Each gene in an Evolution Strategies is composed of a value plus an standard
deviation, sigma, used for mutation*/
struct eoESGene {
double val, sigma;
eoESGene( double _val = 0, double _sigma = 0 ): val( _val ), sigma( _sigma ) {};
};
/// Tricky operator to avoid errors in some VC++ systems, namely VC 5.0 SP3
bool operator < ( eoESGene _e1, eoESGene _e2 ) {
return _e1.val < _e2.val;
}
/// Tricky operator to avoid errors in some VC++ systems
bool operator == ( eoESGene _e1, eoESGene _e2 ) {
return ( _e1.val == _e2.val ) && ( _e1.sigma == _e2.sigma ) ;
}
///
ostream & operator << ( ostream& _s, const eoESGene& _e ) {
_s << _e.val << ", " << _e.sigma << " | ";
return _s;
}
/// Dummy >>
istream & operator >> ( istream& _s, const eoESGene& _e ) {
_s >> _e.val;
_s >> _e.sigma;
return _s;
}
/** Basic chromosome for evolution strategies (ES), as defined by Rechenberg and
Schwefel. Each chromosomes is composed of "genes"; each one of then is an eoESGene
@see eoESGene
*/
template <typename fitT = float >
class eoESChrom: public eoVector<eoESGene, fitT> {
public:
/// Basic ctor
eoESChrom( ):eoVector<eoESGene, fitT>() {};
/** Ctor using a couple of random number generators
@param _size Lineal length of the object
@param _rnd a random number generator, which returns a random value each time it´s called.
@param _rndS another one, for the sigma
*/
eoESChrom( unsigned _size, eoRnd<double>& _rnd, eoRnd<double>& _rndS )
: eoVector<eoESGene, fitT>( _size ){
for ( iterator i = begin(); i != end(); i ++ ) {
i->val = _rnd();
i->sigma = _rndS();
}
};
/// Copy ctor
eoESChrom( const eoESChrom& _eoes): eoVector<eoESGene, fitT>( _eoes ) {};
/// Assignment operator
const eoESChrom& operator =( const eoESChrom & _eoes ) {
if ( this != &_eoes ){
eoVector<eoESGene, fitT>::operator=( _eoes );
}
return *this;
}
///
~eoESChrom() {};
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoESChrom";};
//@}
};
//@}
#endif

View file

@ -1,270 +1,271 @@
// -*- 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 <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 ) {}
/// copy constructor
eoESFullChrom( const eoESFullChrom& _eo ):
eoVector<double, fitT> ( _eo ), // ObjVar ( _eo.ObjVar ),
StdDev ( _eo.StdDev ), CorCff( _eo.CorCff ), verbose( _eo.verbose ),
ObjMin( _eo.ObjMin ), ObjMax(_eo.ObjMax ), StdDevInit( _eo.StdDevInit ) {}
/* another constructor, for compatibility reasons */
eoESFullChrom(istream& _s) {cout << "Not Yet implemented\n";exit(1);};
/* And now the useful constructor: from a parser (should be in the
factory, if such a thing exists one day for eoESFullChrom
*/
eoESFullChrom(Parser & 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
// -*- 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 <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 ) {}
/// copy constructor
eoESFullChrom( const eoESFullChrom& _eo ):
eoVector<double, fitT> ( _eo ), // ObjVar ( _eo.ObjVar ),
StdDev ( _eo.StdDev ), CorCff( _eo.CorCff ), verbose( _eo.verbose ),
ObjMin( _eo.ObjMin ), ObjMax(_eo.ObjMax ), StdDevInit( _eo.StdDevInit ) {}
/* another constructor, for compatibility reasons */
eoESFullChrom(istream& _s) {cout << "Not Yet implemented\n";exit(1);};
/* And now the useful constructor: from a parser (should be in the
factory, if such a thing exists one day for eoESFullChrom
*/
eoESFullChrom(Parser & 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
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

@ -1,84 +1,85 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoEasyEA.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 _eoEasyEA_h
#define _eoEasyEA_h
//-----------------------------------------------------------------------------
#include <eoGeneration.h> // eoPop
#include <eoTerm.h>
/** EOEasyEA:
An easy-to-use evolutionary algorithm; you can use any chromosome,
and any selection transformation, merging and evaluation
algorithms; you can even change in runtime parameters of those
sub-algorithms
*/
template<class Chrom> class eoEasyEA: public eoAlgo<Chrom>
{
public:
/// Constructor.
eoEasyEA(eoBinPopOp<Chrom>& _select,
eoMonPopOp<Chrom>& _transform,
eoBinPopOp<Chrom>& _replace,
eoEvalFunc<Chrom>& _evaluator,
eoTerm<Chrom>& _terminator)
:step(_select, _transform, _replace, _evaluator),
terminator( _terminator){};
/// Constructor from an already created generation
eoEasyEA(eoGeneration<Chrom>& _gen,
eoTerm<Chrom>& _terminator):
step(_gen),
terminator( _terminator){};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<Chrom>& pop) {
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoEasyEA.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 _eoEasyEA_h
#define _eoEasyEA_h
//-----------------------------------------------------------------------------
#include <eoGeneration.h> // eoPop
#include <eoTerm.h>
/** EOEasyEA:
An easy-to-use evolutionary algorithm; you can use any chromosome,
and any selection transformation, merging and evaluation
algorithms; you can even change in runtime parameters of those
sub-algorithms
*/
template<class Chrom> class eoEasyEA: public eoAlgo<Chrom>
{
public:
/// Constructor.
eoEasyEA(eoBinPopOp<Chrom>& _select,
eoMonPopOp<Chrom>& _transform,
eoBinPopOp<Chrom>& _replace,
eoEvalFunc<Chrom>& _evaluator,
eoTerm<Chrom>& _terminator)
:step(_select, _transform, _replace, _evaluator),
terminator( _terminator){};
/// Constructor from an already created generation
eoEasyEA(eoGeneration<Chrom>& _gen,
eoTerm<Chrom>& _terminator):
step(_gen),
terminator( _terminator){};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<Chrom>& pop) {
while ( terminator( pop ) ) {
try
{
step(pop);
}
catch (exception& e)
{
string s = e.what();
s.append( " in eoEasyEA ");
throw runtime_error( s );
}
try
{
step(pop);
}
catch (exception& e)
{
string s = e.what();
s.append( " in eoEasyEA ");
throw runtime_error( s );
}
} // while
}
/// Class name.
string className() const { return "eoEasyEA"; }
private:
eoGeneration<Chrom> step;
eoTerm<Chrom>& terminator;
};
//-----------------------------------------------------------------------------
#endif eoEasyEA_h
}
/// Class name.
string className() const { return "eoEasyEA"; }
private:
eoGeneration<Chrom> step;
eoTerm<Chrom>& terminator;
};
//-----------------------------------------------------------------------------
#endif eoEasyEA_h

View file

@ -1,59 +1,60 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoEvalFuncPtr.h
Converts a classical C fitness evaluation function into a fitness
evaluation object
(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 EOEVALFUNCPTR_H
#define EOEVALFUNCPTR_H
#include <eoEvalFunc.h>
/** EOEvalFuncPtr: 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 eoEvalFuncPtr: public eoEvalFunc<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.
*/
eoEvalFuncPtr( EOFitT (* _eval)( const EOT& ) )
: eoEvalFunc<EOT>(), evalFunc( _eval ) {};
/// Effectively applies the evaluation function to an EO
virtual void operator() ( EOT & _eo ) const {
_eo.fitness((*evalFunc)( _eo ));
};
private:
EOFitT (* evalFunc )( const EOT& );
};
#endif
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoEvalFuncPtr.h
Converts a classical C fitness evaluation function into a fitness
evaluation object
(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 EOEVALFUNCPTR_H
#define EOEVALFUNCPTR_H
#include <eoEvalFunc.h>
/** EOEvalFuncPtr: 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 eoEvalFuncPtr: public eoEvalFunc<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.
*/
eoEvalFuncPtr( EOFitT (* _eval)( const EOT& ) )
: eoEvalFunc<EOT>(), evalFunc( _eval ) {};
/// Effectively applies the evaluation function to an EO
virtual void operator() ( EOT & _eo ) const {
_eo.fitness((*evalFunc)( _eo ));
};
private:
EOFitT (* evalFunc )( const EOT& );
};
#endif

View file

@ -1,69 +1,69 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoException.h
Exceptions that are possibly thrown at initialization and such should be
defined here
(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 eoException_h
#define eoException_h
#include <exception>
#include "eoObject.h"
struct eoException
{
eoException() {}
eoException(const eoObject& caller) : who_caught_it(caller.className()) {}
std::string who(void) const { return who_caught_it; }
virtual std::string what(void) const{ return "";}
private :
std::string who_caught_it;
};
struct eoFitnessException : public eoException
{
eoFitnessException() : eoException() {}
eoFitnessException(const eoObject& caller) : eoException(caller) {}
};
struct eoNegativeFitnessException : public eoFitnessException
{
eoNegativeFitnessException() : eoFitnessException() {}
eoNegativeFitnessException(const eoObject& caller) : eoFitnessException(caller) {}
std::string what(void) const { return "negative fitness encountered"; }
};
struct eoMinimizingFitnessException : public eoFitnessException
{
eoMinimizingFitnessException() : eoFitnessException() {}
eoMinimizingFitnessException(const eoObject& caller) : eoFitnessException(caller) {}
std::string what(void) const { return "smaller fitness is better fitness, which is quite inappropriate here"; }
};
#endif
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoException.h
Exceptions that are possibly thrown at initialization and such should be
defined here.
(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 eoException_h
#define eoException_h
#include <exception>
#include "eoObject.h"
struct eoException
{
eoException() {}
eoException(const eoObject& caller) : who_caught_it(caller.className()) {}
std::string who(void) const { return who_caught_it; }
virtual std::string what(void) const{ return "";}
private :
std::string who_caught_it;
};
struct eoFitnessException : public eoException
{
eoFitnessException() : eoException() {}
eoFitnessException(const eoObject& caller) : eoException(caller) {}
};
struct eoNegativeFitnessException : public eoFitnessException
{
eoNegativeFitnessException() : eoFitnessException() {}
eoNegativeFitnessException(const eoObject& caller) : eoFitnessException(caller) {}
std::string what(void) const { return "negative fitness encountered"; }
};
struct eoMinimizingFitnessException : public eoFitnessException
{
eoMinimizingFitnessException() : eoFitnessException() {}
eoMinimizingFitnessException(const eoObject& caller) : eoFitnessException(caller) {}
std::string what(void) const { return "smaller fitness is better fitness, which is quite inappropriate here"; }
};
#endif

View file

@ -1,64 +1,65 @@
// -*- 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 <eoTerm.h>
/** Fitness termination: terminates after a the difference between the
fitness of the best individual and a maximum fitness to achieve is less
than certain number called epsilon., i.e., |maximum-fitness|<epsilon
*/
template< class EOT>
class eoFitTerm: public eoTerm<EOT> {
public:
/// Ctors/dtors
eoFitTerm( const float _maximum, const float _epsilon )
: eoTerm<EOT> (), maximum( _maximum ), epsilon(_epsilon){};
/// Copy ctor
eoFitTerm( const eoFitTerm& _t )
: eoTerm<EOT> ( _t ), maximum( _t.maximum ),
epsilon(_t.epsilon){};
///
virtual ~eoFitTerm() {};
/** Returns false when a certain number of generations is
* reached */
virtual bool operator() ( const eoPop<EOT>& _vEO ) {
float bestFitness=_vEO[0].fitness();
float dif=bestFitness-maximum;
dif=(dif<0)?-dif:dif;
return (dif>epsilon ) || (bestFitness > maximum);
}
private:
float maximum, epsilon;
};
#endif
// -*- 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 <eoTerm.h>
/** Fitness termination: terminates after a the difference between the
fitness of the best individual and a maximum fitness to achieve is less
than certain number called epsilon., i.e., |maximum-fitness|<epsilon
*/
template< class EOT>
class eoFitTerm: public eoTerm<EOT> {
public:
/// Ctors/dtors
eoFitTerm( const float _maximum, const float _epsilon )
: eoTerm<EOT> (), maximum( _maximum ), epsilon(_epsilon){};
/// Copy ctor
eoFitTerm( const eoFitTerm& _t )
: eoTerm<EOT> ( _t ), maximum( _t.maximum ),
epsilon(_t.epsilon){};
///
virtual ~eoFitTerm() {};
/** Returns false when a certain number of generations is
* reached */
virtual bool operator() ( const eoPop<EOT>& _vEO ) {
float bestFitness=_vEO[0].fitness();
float dif=bestFitness-maximum;
dif=(dif<0)?-dif:dif;
return (dif>epsilon ) || (bestFitness > maximum);
}
private:
float maximum, epsilon;
};
#endif

View file

@ -1,54 +1,55 @@
// 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
//-----------------------------------------------------------------------------
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
// 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
//-----------------------------------------------------------------------------
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

@ -1,58 +1,59 @@
//-----------------------------------------------------------------------------
// eoBreeder.h
//-----------------------------------------------------------------------------
#ifndef eoGopBreeder_h
#define eoGopBreeder_h
//-----------------------------------------------------------------------------
/*****************************************************************************
* eoBreeder: transforms a population using genetic operators. *
* For every operator there is a rated to be applyed. *
*****************************************************************************/
#include "eoPopOps.h"
#include "eoGOpSelector.h"
#include "eoIndiSelector.h"
#include "eoBackInserter.h"
template<class EOT>
class eoGOpBreeder: public eoMonPopOp<EOT>
{
public:
/// Default constructor.
eoGOpBreeder( eoGOpSelector<EOT>& _opSel,
eoPopIndiSelector<EOT>& _selector)
: opSel( _opSel ), selector(_selector)
{}
/// Destructor.
virtual ~eoGOpBreeder() {}
/**
* Enlarges the population.
* @param pop The population to be transformed.
*/
void operator()(eoPop<EOT>& _pop)
{
int size = _pop.size();
for (unsigned i = 0; i < size; i++)
{ // and the one liner
opSel.selectOp()(selector(_pop,size, i), inserter(_pop));
}
}
/// The class name.
string classname() const { return "eoGOpBreeder"; }
private:
eoGOpSelector<EOT>& opSel;
eoPopIndiSelector<EOT>& selector;
// the inserter can be local as there's no point in changing it from the outside
eoBackInserter<EOT> inserter;
};
#endif eoBreeder_h
//-----------------------------------------------------------------------------
// eoBreeder.h
//-----------------------------------------------------------------------------
#ifndef eoGopBreeder_h
#define eoGopBreeder_h
//-----------------------------------------------------------------------------
/*****************************************************************************
* eoBreeder: transforms a population using genetic operators. *
* For every operator there is a rated to be applyed. *
*****************************************************************************/
#include "eoPopOps.h"
#include "eoGOpSelector.h"
#include "eoIndiSelector.h"
#include "eoBackInserter.h"
template<class EOT>
class eoGOpBreeder: public eoMonPopOp<EOT>
{
public:
/// Default constructor.
eoGOpBreeder( eoGOpSelector<EOT>& _opSel,
eoPopIndiSelector<EOT>& _selector)
: opSel( _opSel ), selector(_selector)
{}
/// Destructor.
virtual ~eoGOpBreeder() {}
/**
* Enlarges the population.
* @param pop The population to be transformed.
*/
void operator()(eoPop<EOT>& _pop)
{
int size = _pop.size();
for (unsigned i = 0; i < size; i++)
{ // and the one liner
opSel.selectOp()(selector(_pop,size, i), inserter(_pop));
}
}
/// The class name.
string classname() const { return "eoGOpBreeder"; }
private:
eoGOpSelector<EOT>& opSel;
eoPopIndiSelector<EOT>& selector;
// the inserter can be local as there's no point in changing it from the outside
eoBackInserter<EOT> inserter;
};
#endif eoBreeder_h

View file

@ -1,173 +1,174 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoGOpSelector.h
Base class for generalized (n-inputs, n-outputs) operator selectors.
Includes code and variables that contain operators and rates.
Also included eoProportionalGOpSelector and eoSequentialGOpSelector, that offer
a few concrete implementations.
(c) Maarten Keijzer, 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 eoGOpSelector_h
#define eoGOpSelector_h
//-----------------------------------------------------------------------------
#include <list>
#include "eoOpSelector.h"
#include "eoWrappedOps.h" // for eoCombinedOp
#include "eoRNG.h"
using namespace std;
/** Base class for alternative selectors, which use the generalized operator
interface. eoGOpBreeders expects this class */
template<class EOT>
class eoGOpSelector: public eoOpSelector<EOT>, public vector<eoGeneralOp<EOT>*>
{
public:
typedef eoOpSelector<EOT>::ID ID;
/// Dtor
virtual ~eoGOpSelector() {
for ( list< eoGeneralOp<EOT>* >::iterator i= ownOpList.begin();
i != ownOpList.end(); i++ ) {
delete *i;
}
}
/// Add any kind of operator to the operator mix, with an argument
virtual ID addOp( eoOp<EOT>& _op, float _arg );
// implementation can be found below
/** Retrieve the operator using its integer handle
@param _id The id number. Should be a valid id, or an exception
will be thrown
@return a reference of the operator corresponding to that id.
*/
virtual const eoOp<EOT>& getOp( ID _id )
{
return *operator[](_id);
}
///
virtual void deleteOp( ID _id );
// implemented below
///
virtual eoOp<EOT>* Op()
{
return &selectOp();
}
///
virtual eoGeneralOp<EOT>& selectOp() = 0;
///
virtual string className() const { return "eoGOpSelector"; };
///
void printOn(ostream& _os) const {}
// _os << className().c_str() << endl;
// for ( unsigned i=0; i!= rates.size(); i++ ) {
// _os << *(operator[](i)) << "\t" << rates[i] << endl;
// }
//}
const vector<float>& getRates(void) const { return rates; }
private :
vector<float> rates;
list< eoGeneralOp<EOT>* > ownOpList;
};
/* Implementation of longish functions defined above */
template <class EOT>
inline eoOpSelector<EOT>::ID eoGOpSelector<EOT>::addOp( eoOp<EOT>& _op, float _arg )
{
eoGeneralOp<EOT>* op;
if (_op.getType() == eoOp<EOT>::general)
{
op = static_cast<eoGeneralOp<EOT>*>(&_op);
}
else
{
// if it's not a general op, it's a "old" op; create a wrapped op from it
// and keep it on a list to delete them afterwards
// will use auto_ptr when they're readily available
switch(_op.getType())
{
case eoOp<EOT>::unary :
op= new eoWrappedMonOp<EOT>(static_cast<eoMonOp<EOT>&>(_op));
break;
case eoOp<EOT>::binary :
op = new eoWrappedBinOp<EOT>(static_cast<eoBinOp<EOT>&>(_op));
case eoOp<EOT>::quadratic :
op = new eoWrappedQuadraticOp<EOT>(static_cast<eoQuadraticOp<EOT>&>(_op));
break;
}
ownOpList.push_back( op );
}
// Now 'op' is a general operator, either because '_op' was one or
// because we wrapped it in an appropriate wrapper in the code above.
iterator result = find(begin(), end(), (eoGeneralOp<EOT>*) 0); // search for nullpointer
if (result == end())
{
push_back(op);
rates.push_back(_arg);
return size();
}
// else
*result = op;
ID id = result - begin();
rates[id] = _arg;
return id;
}
template <class EOT>
inline void eoGOpSelector<EOT>::deleteOp( ID _id )
{
eoGeneralOp<EOT>* op = operator[](_id);
operator[](_id) = 0;
rates[_id] = 0.0;
// check oplist and clear it there too.
list< eoGeneralOp<EOT>* >::iterator it = find(ownOpList.begin(), ownOpList.end(), op);
if(it != ownOpList.end())
{
ownOpList.erase(it);
}
}
#endif eoGOpSelector_h
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoGOpSelector.h
Base class for generalized (n-inputs, n-outputs) operator selectors.
Includes code and variables that contain operators and rates.
Also included eoProportionalGOpSelector and eoSequentialGOpSelector, that offer
a few concrete implementations.
(c) Maarten Keijzer, 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 eoGOpSelector_h
#define eoGOpSelector_h
//-----------------------------------------------------------------------------
#include <list>
#include "eoOpSelector.h"
#include "eoWrappedOps.h" // for eoCombinedOp
#include "eoRNG.h"
using namespace std;
/** Base class for alternative selectors, which use the generalized operator
interface. eoGOpBreeders expects this class */
template<class EOT>
class eoGOpSelector: public eoOpSelector<EOT>, public vector<eoGeneralOp<EOT>*>
{
public:
typedef eoOpSelector<EOT>::ID ID;
/// Dtor
virtual ~eoGOpSelector() {
for ( list< eoGeneralOp<EOT>* >::iterator i= ownOpList.begin();
i != ownOpList.end(); i++ ) {
delete *i;
}
}
/// Add any kind of operator to the operator mix, with an argument
virtual ID addOp( eoOp<EOT>& _op, float _arg );
// implementation can be found below
/** Retrieve the operator using its integer handle
@param _id The id number. Should be a valid id, or an exception
will be thrown
@return a reference of the operator corresponding to that id.
*/
virtual const eoOp<EOT>& getOp( ID _id )
{
return *operator[](_id);
}
///
virtual void deleteOp( ID _id );
// implemented below
///
virtual eoOp<EOT>* Op()
{
return &selectOp();
}
///
virtual eoGeneralOp<EOT>& selectOp() = 0;
///
virtual string className() const { return "eoGOpSelector"; };
///
void printOn(ostream& _os) const {}
// _os << className().c_str() << endl;
// for ( unsigned i=0; i!= rates.size(); i++ ) {
// _os << *(operator[](i)) << "\t" << rates[i] << endl;
// }
//}
const vector<float>& getRates(void) const { return rates; }
private :
vector<float> rates;
list< eoGeneralOp<EOT>* > ownOpList;
};
/* Implementation of longish functions defined above */
template <class EOT>
inline eoOpSelector<EOT>::ID eoGOpSelector<EOT>::addOp( eoOp<EOT>& _op, float _arg )
{
eoGeneralOp<EOT>* op;
if (_op.getType() == eoOp<EOT>::general)
{
op = static_cast<eoGeneralOp<EOT>*>(&_op);
}
else
{
// if it's not a general op, it's a "old" op; create a wrapped op from it
// and keep it on a list to delete them afterwards
// will use auto_ptr when they're readily available
switch(_op.getType())
{
case eoOp<EOT>::unary :
op= new eoWrappedMonOp<EOT>(static_cast<eoMonOp<EOT>&>(_op));
break;
case eoOp<EOT>::binary :
op = new eoWrappedBinOp<EOT>(static_cast<eoBinOp<EOT>&>(_op));
case eoOp<EOT>::quadratic :
op = new eoWrappedQuadraticOp<EOT>(static_cast<eoQuadraticOp<EOT>&>(_op));
break;
}
ownOpList.push_back( op );
}
// Now 'op' is a general operator, either because '_op' was one or
// because we wrapped it in an appropriate wrapper in the code above.
iterator result = find(begin(), end(), (eoGeneralOp<EOT>*) 0); // search for nullpointer
if (result == end())
{
push_back(op);
rates.push_back(_arg);
return size();
}
// else
*result = op;
ID id = result - begin();
rates[id] = _arg;
return id;
}
template <class EOT>
inline void eoGOpSelector<EOT>::deleteOp( ID _id )
{
eoGeneralOp<EOT>* op = operator[](_id);
operator[](_id) = 0;
rates[_id] = 0.0;
// check oplist and clear it there too.
list< eoGeneralOp<EOT>* >::iterator it = find(ownOpList.begin(), ownOpList.end(), op);
if(it != ownOpList.end())
{
ownOpList.erase(it);
}
}
#endif eoGOpSelector_h

View file

@ -1,82 +1,83 @@
// -*- 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 <eoTerm.h>
/** Generational termination: terminates after a number of generations
*/
template< class EOT>
class eoGenTerm: public eoTerm<EOT> {
public:
/// Ctors/dtors
eoGenTerm( unsigned _totalGens)
: eoTerm<EOT> (), repTotalGenerations( _totalGens ),
thisGeneration(0){};
/// Copy Ctor
eoGenTerm( const eoGenTerm& _t)
: eoTerm<EOT> ( _t ), repTotalGenerations( _t.repTotalGenerations ),
thisGeneration(0){};
/// Assignment Operator
const eoGenTerm& operator = ( const eoGenTerm& _t) {
if ( &_t != this ) {
repTotalGenerations = _t.repTotalGenerations;
thisGeneration = 0;
}
return *this;
}
/// Dtor
virtual ~eoGenTerm() {};
/** 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;
};
private:
unsigned repTotalGenerations, thisGeneration;
};
#endif
// -*- 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 <eoTerm.h>
/** Generational termination: terminates after a number of generations
*/
template< class EOT>
class eoGenTerm: public eoTerm<EOT> {
public:
/// Ctors/dtors
eoGenTerm( unsigned _totalGens)
: eoTerm<EOT> (), repTotalGenerations( _totalGens ),
thisGeneration(0){};
/// Copy Ctor
eoGenTerm( const eoGenTerm& _t)
: eoTerm<EOT> ( _t ), repTotalGenerations( _t.repTotalGenerations ),
thisGeneration(0){};
/// Assignment Operator
const eoGenTerm& operator = ( const eoGenTerm& _t) {
if ( &_t != this ) {
repTotalGenerations = _t.repTotalGenerations;
thisGeneration = 0;
}
return *this;
}
/// Dtor
virtual ~eoGenTerm() {};
/** 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;
};
private:
unsigned repTotalGenerations, thisGeneration;
};
#endif

View file

@ -1,109 +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
// -*- 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

@ -1,134 +1,134 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoIndiSelector.h
Abstract selection operator, which is used by the eoGeneralOps
to obtain individuals from a source population. It also gives a
direct descended eoPopIndiSelector that can be used to
initialize objects with an eoPop<EOT>. For most uses use eoPopIndividualSelector
rather than eoIndividualSelector to derive from.
(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 eoIndiSelector_h
#define eoIndiSelector_h
/**
* eoIndividualSelector: This class defines the interface
*/
template <class EOT>
class eoIndiSelector
{
public :
eoIndiSelector() {}
virtual ~eoIndiSelector(void) {}
virtual size_t size(void) const = 0;
virtual const EOT& operator[](size_t) const = 0;
virtual const EOT& select(void) = 0;
virtual vector<const EOT*> select(size_t _how_many)
{ // default implementation just calls select a couple of times
// this can be overridden in favour of a more efficient implementation
vector<const EOT*> result(_how_many);
for (int i = 0; i < _how_many; ++i)
{
result[i] = &select();
}
return result;
}
};
/**
* eoPopIndiSelector: Intermediate class for dispensing populations
various useful things can be done with this class:
you can specify how many of the population can ever be dispensed to the
operators, but you can also specify a preference to the first guy being
dispensed. This is useful if you want to perform the operator on a specific
individual.
*/
template <class EOT>
class eoPopIndiSelector : public eoIndiSelector<EOT>
{
public :
eoPopIndiSelector(void) : pop(0), firstChoice(-1), last(0), eoIndiSelector<EOT>() {}
virtual ~eoPopIndiSelector(void) {}
struct eoUnitializedException{};
/** Initialization function
*/
eoPopIndiSelector& operator()(const eoPop<EOT>& _pop, int _end = -1, int _myGuy = -1)
{
pop = &_pop;
last = _end;
if (last < 0 || last > pop->size())
{
last = pop->size();
}
firstChoice = _myGuy;
return *this;
}
size_t size(void) const { valid(); return last; }
const EOT& operator[](size_t _i) const { valid(); return pop->operator[](_i); }
eoPop<EOT>::const_iterator begin(void) const { valid(); return pop->begin(); }
eoPop<EOT>::const_iterator end(void) const { valid(); return pop->end(); }
/// select does the work. Note that it is not virtual. It calls do_select that needs to be implemented by the derived classes
const EOT& select(void)
{
valid();
if (firstChoice < 0 || firstChoice >= size())
{
return do_select(); // let the child figure out what to do
}
const EOT& result = pop->operator[](firstChoice);
firstChoice = -1;
return result;
}
virtual const EOT& do_select(void) = 0;
private :
void valid(void) const
{
if (pop == 0)
throw eoUnitializedException();
}
const eoPop<EOT>* pop; // need a pointer as this the pop argument can be re-instated
int last;
int firstChoice;
};
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoIndiSelector.h
Abstract selection operator, which is used by the eoGeneralOps
to obtain individuals from a source population. It also gives a
direct descended eoPopIndiSelector that can be used to
initialize objects with an eoPop<EOT>. For most uses use eoPopIndividualSelector
rather than eoIndividualSelector to derive from.
(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 eoIndiSelector_h
#define eoIndiSelector_h
/**
* eoIndividualSelector: This class defines the interface
*/
template <class EOT>
class eoIndiSelector
{
public :
eoIndiSelector() {}
virtual ~eoIndiSelector(void) {}
virtual size_t size(void) const = 0;
virtual const EOT& operator[](size_t) const = 0;
virtual const EOT& select(void) = 0;
virtual vector<const EOT*> select(size_t _how_many)
{ // default implementation just calls select a couple of times
// this can be overridden in favour of a more efficient implementation
vector<const EOT*> result(_how_many);
for (int i = 0; i < _how_many; ++i)
{
result[i] = &select();
}
return result;
}
};
/**
* eoPopIndiSelector: Intermediate class for dispensing populations
various useful things can be done with this class:
you can specify how many of the population can ever be dispensed to the
operators, but you can also specify a preference to the first guy being
dispensed. This is useful if you want to perform the operator on a specific
individual.
*/
template <class EOT>
class eoPopIndiSelector : public eoIndiSelector<EOT>
{
public :
eoPopIndiSelector(void) : pop(0), firstChoice(-1), last(0), eoIndiSelector<EOT>() {}
virtual ~eoPopIndiSelector(void) {}
struct eoUnitializedException{};
/** Initialization function
*/
eoPopIndiSelector& operator()(const eoPop<EOT>& _pop, int _end = -1, int _myGuy = -1)
{
pop = &_pop;
last = _end;
if (last < 0 || last > pop->size())
{
last = pop->size();
}
firstChoice = _myGuy;
return *this;
}
size_t size(void) const { valid(); return last; }
const EOT& operator[](size_t _i) const { valid(); return pop->operator[](_i); }
eoPop<EOT>::const_iterator begin(void) const { valid(); return pop->begin(); }
eoPop<EOT>::const_iterator end(void) const { valid(); return pop->end(); }
/// select does the work. Note that it is not virtual. It calls do_select that needs to be implemented by the derived classes
const EOT& select(void)
{
valid();
if (firstChoice < 0 || firstChoice >= size())
{
return do_select(); // let the child figure out what to do
}
const EOT& result = pop->operator[](firstChoice);
firstChoice = -1;
return result;
}
virtual const EOT& do_select(void) = 0;
private :
void valid(void) const
{
if (pop == 0)
throw eoUnitializedException();
}
const eoPop<EOT>* pop; // need a pointer as this the pop argument can be re-instated
int last;
int firstChoice;
};
#endif

View file

@ -1,92 +1,93 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoInserter.h
Abstract population insertion operator, which is used by the eoGeneralOps
to insert the results in the (intermediate) population. It also contains
a direct descended eoPopInserter that defines a convenient inbetween class
for working with eoPop<EOT>. The user will most likely derive from eoPopInserter
rather than eoInserter.
(c) Maarten Keijzer (mak@dhi.dk) 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 eoInserter_h
#define eoInserter_h
#include "eoPop.h"
/**
* eoInserter: Interface class that enables an operator to insert
new individuals into the (intermediate) population.
*/
template <class EOT>
class eoInserter : public eoObject
{
public :
virtual ~eoInserter() {}
struct eoInserterException{};
virtual void insert(const EOT&) = 0; // can throw an eoInserterException
};
/**
* eoPopInserter: In-between class that defines an initialization
* of the eoIndividualInserter.
*/
template <class EOT>
class eoPopInserter : public eoInserter<EOT>
{
public :
eoPopInserter(void) : thePop(0), eoInserter<EOT>() {}
/// Binds the population to this class. This is an initialization routine used by breeders
eoInserter<EOT>& operator()(eoPop<EOT>& _pop)
{
thePop = &_pop;
return *this;
}
protected :
eoPop<EOT>& pop(void) const { valid(); return *thePop; }
private :
void valid(void) const
{
if (thePop == 0)
throw eoInserterException();
}
// Need a pointer as the inserter should be able to bind to different populations.
// This is caused by the 'one template parameter only' convention in EO.
eoPop<EOT>* thePop;
// If eoGOpBreeder could be templatized over the inserter and the selector,
// the pop could be a ref as this class could be created every time it is applied
// and subsequently would get the population through the constructor
};
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoInserter.h
Abstract population insertion operator, which is used by the eoGeneralOps
to insert the results in the (intermediate) population. It also contains
a direct descended eoPopInserter that defines a convenient inbetween class
for working with eoPop<EOT>. The user will most likely derive from eoPopInserter
rather than eoInserter.
(c) Maarten Keijzer (mak@dhi.dk) 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 eoInserter_h
#define eoInserter_h
#include "eoPop.h"
/**
* eoInserter: Interface class that enables an operator to insert
new individuals into the (intermediate) population.
*/
template <class EOT>
class eoInserter : public eoObject
{
public :
virtual ~eoInserter() {}
struct eoInserterException{};
virtual void insert(const EOT&) = 0; // can throw an eoInserterException
};
/**
* eoPopInserter: In-between class that defines an initialization
* of the eoIndividualInserter.
*/
template <class EOT>
class eoPopInserter : public eoInserter<EOT>
{
public :
eoPopInserter(void) : thePop(0), eoInserter<EOT>() {}
/// Binds the population to this class. This is an initialization routine used by breeders
eoInserter<EOT>& operator()(eoPop<EOT>& _pop)
{
thePop = &_pop;
return *this;
}
protected :
eoPop<EOT>& pop(void) const { valid(); return *thePop; }
private :
void valid(void) const
{
if (thePop == 0)
throw eoInserterException();
}
// Need a pointer as the inserter should be able to bind to different populations.
// This is caused by the 'one template parameter only' convention in EO.
eoPop<EOT>* thePop;
// If eoGOpBreeder could be templatized over the inserter and the selector,
// the pop could be a ref as this class could be created every time it is applied
// and subsequently would get the population through the constructor
};
#endif

View file

@ -1,61 +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 <eoUniform.h>
#include <eoOp.h>
/// Kill eliminates a gen in a chromosome
template <class EOT >
class eoKill: public eoMonOp<EOT> {
public:
///
eoKill( )
: eoMonOp< EOT >(){};
/// needed virtual dtor
virtual ~eoKill() {};
///
virtual void operator()( EOT& _eo ) const {
eoUniform<unsigned> uniform( 0, _eo.length() );
unsigned pos = uniform( );
_eo.deleteGene( pos );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoKill";};
//@}
};
#endif
// -*- 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 <eoUniform.h>
#include <eoOp.h>
/// Kill eliminates a gen in a chromosome
template <class EOT >
class eoKill: public eoMonOp<EOT> {
public:
///
eoKill( )
: eoMonOp< EOT >(){};
/// needed virtual dtor
virtual ~eoKill() {};
///
virtual void operator()( EOT& _eo ) const {
eoUniform<unsigned> uniform( 0, _eo.length() );
unsigned pos = uniform( );
_eo.deleteGene( pos );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoKill";};
//@}
};
#endif

View file

@ -1,97 +1,98 @@
// -*- 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 <functional> //
#include <numeric> // accumulate
#include "selectors.h"
#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 eoBinPopOp<EOT>
{
public:
/// (Default) Constructor.
eoLottery(const float& _rate = 1.0): eoBinPopOp<EOT>(), rate(_rate)
{
if (minimizing_fitness<EOT>())
{
eoMinimizingFitnessException up(*this);
throw up; // :-)
}
}
/** 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()( eoPop<EOT>& pop, eoPop<EOT>& breeders)
{
int target = (int)(rate * pop.size());
// 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);
}
// 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
// -*- 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 <functional> //
#include <numeric> // accumulate
#include "selectors.h"
#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 eoBinPopOp<EOT>
{
public:
/// (Default) Constructor.
eoLottery(const float& _rate = 1.0): eoBinPopOp<EOT>(), rate(_rate)
{
if (minimizing_fitness<EOT>())
{
eoMinimizingFitnessException up(*this);
throw up; // :-)
}
}
/** 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()( eoPop<EOT>& pop, eoPop<EOT>& breeders)
{
int target = (int)(rate * pop.size());
// 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);
}
// 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

@ -1,99 +1,100 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoMultiBinOp.h
// Class that combines several binary or unary operators
// (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 _EOMULTIBINOP_h
#define _EOMULTIBINOP_h
#include <iterator>
#include <eoOp.h>
/** MultiMonOp combines several monary operators. By itself, it does nothing to the
EO it´s handled*/
template <class EOT>
class eoMultiBinOp: public eoBinOp<EOT> {
public:
/// Ctor from an already existing op
eoMultiBinOp( const eoBinOp<EOT>* _op )
: eoBinOp< EOT >( ), vOp(){
vOp.push_back( _op );
};
///
eoMultiBinOp( )
: eoBinOp< EOT >( ), vOp(){};
/// Ads a new operator
void adOp( const eoOp<EOT>* _op ){
vOp.push_back( _op );
};
/// needed virtual dtor
virtual ~eoMultiBinOp() {};
///
/// Applies all operators to the EO
virtual void operator()( EOT& _eo1, EOT& _eo2 ) const {
if ( vOp.begin() != vOp.end() ) { // which would mean it's empty
for ( vector< const eoOp<EOT>* >::const_iterator i = vOp.begin();
i != vOp.end(); i++ ) {
// Admits only unary or binary operator
switch ((*i)->readArity()) {
case unary:
{
const eoMonOp<EOT>* monop = static_cast<const eoMonOp<EOT>* >(*i);
(*monop)( _eo1 );
(*monop)( _eo2 );
break;
}
case binary:
{
const eoBinOp<EOT>* binop = static_cast<const eoBinOp<EOT>* >(*i);
(*binop)( _eo1, _eo2 );
break;
}
}
}
}
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoMultiBinOp";};
//@}
private:
/// uses pointers to base class since operators can be unary or binary
vector< const eoOp<EOT>* > vOp;
};
#endif
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoMultiBinOp.h
// Class that combines several binary or unary operators
// (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 _EOMULTIBINOP_h
#define _EOMULTIBINOP_h
#include <iterator>
#include <eoOp.h>
/** MultiMonOp combines several monary operators. By itself, it does nothing to the
EO it´s handled*/
template <class EOT>
class eoMultiBinOp: public eoBinOp<EOT> {
public:
/// Ctor from an already existing op
eoMultiBinOp( const eoBinOp<EOT>* _op )
: eoBinOp< EOT >( ), vOp(){
vOp.push_back( _op );
};
///
eoMultiBinOp( )
: eoBinOp< EOT >( ), vOp(){};
/// Ads a new operator
void adOp( const eoOp<EOT>* _op ){
vOp.push_back( _op );
};
/// needed virtual dtor
virtual ~eoMultiBinOp() {};
///
/// Applies all operators to the EO
virtual void operator()( EOT& _eo1, EOT& _eo2 ) const {
if ( vOp.begin() != vOp.end() ) { // which would mean it's empty
for ( vector< const eoOp<EOT>* >::const_iterator i = vOp.begin();
i != vOp.end(); i++ ) {
// Admits only unary or binary operator
switch ((*i)->readArity()) {
case unary:
{
const eoMonOp<EOT>* monop = static_cast<const eoMonOp<EOT>* >(*i);
(*monop)( _eo1 );
(*monop)( _eo2 );
break;
}
case binary:
{
const eoBinOp<EOT>* binop = static_cast<const eoBinOp<EOT>* >(*i);
(*binop)( _eo1, _eo2 );
break;
}
}
}
}
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoMultiBinOp";};
//@}
private:
/// uses pointers to base class since operators can be unary or binary
vector< const eoOp<EOT>* > vOp;
};
#endif

View file

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

View file

@ -1,90 +1,91 @@
// -*- 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>
#include <eoUniform.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
// -*- 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>
#include <eoUniform.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

@ -1,66 +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 <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
/** -*- 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 <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

@ -1,86 +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
//-----------------------------------------------------------------------------
// 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

@ -1,88 +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 <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
// -*- 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 <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

View file

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

View file

@ -1,235 +1,236 @@
// -*- 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 _eoOp_H
#define _eoOp_H
#include <eoObject.h>
#include <eoPrintable.h>
/** @name Genetic operators
What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with
eoOp as father and eoMonOp (monary or unary operator) and eoBinOp and eoQuadraticOp (binary operators)
as siblings). Nobody should subclass eoOp, you should subclass eoGeneralOp, eoBinOp, eoQuadraticOp or eoMonOp,
those are the ones actually used here.\\
#eoOp#s are only printable objects, so if you want to build them from a file, it has to
be done in another class, namely factories. Each hierarchy of #eoOp#s should have its own
factory, which know how to build them from a description in a file.
@author GeNeura Team
@version 0.1
@see eoOpFactory
*/
/** Abstract data types for EO operators.
* Genetic operators act on chromosomes, changing them. The type to instantiate them should
* be an eoObject, but in any case, they are type-specific; each kind of evolvable object
* can have its own operators
*/
template<class EOType>
class eoOp: public eoObject, public eoPrintable {
public:
//@{
enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3};
///
/// Ctor
eoOp(OpType _type)
:opType( _type ) {};
/// Copy Ctor
eoOp( const eoOp& _eop )
:opType( _eop.opType ) {};
/// Needed virtual destructor
virtual ~eoOp(){};
/// getType: number of operands it takes and individuals it produces
OpType getType() const {return opType;};
/** @name Methods from eoObject */
//@{
/**
* Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream.
*/
virtual void printOn(ostream& _os) const {
_os << className().c_str();
// _os << arity;
};
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoOp";};
//@}
private:
/// OpType is the type of the operator: how many operands it takes and how many it produces
OpType opType;
};
/** Binary genetic operator: subclasses eoOp, and defines
basically the operator() with two operands
*/
template<class EOType>
class eoBinOp: public eoOp<EOType> {
public:
/// Ctor
eoBinOp()
:eoOp<EOType>( binary ) {};
/// Copy Ctor
eoBinOp( const eoBinOp& _ebop )
: eoOp<EOType>( _ebop ){};
/// Dtor
~eoBinOp () {};
/** applies operator, to the object. Modifies only the first operand.
*/
virtual void operator()( EOType& _eo1, const EOType& _eo2 ) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoBinOp";};
//@}
};
/** Quadratic genetic operator: subclasses eoOp, and defines
basically the operator() with two operands
*/
template<class EOType>
class eoQuadraticOp: public eoOp<EOType> {
public:
/// Ctor
eoQuadraticOp()
:eoOp<EOType>( eoOp<EOType>::quadratic ) {};
/// Copy Ctor
eoQuadraticOp( const eoQuadraticOp& _ebop )
: eoOp<EOType>( _ebop ){};
/// Dtor
~eoQuadraticOp() {};
/** applies operator, to the object. Modifies both operands.
*/
virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoBinOp";};
//@}
};
/** eoMonOp is the monary operator: genetic operator that takes
only one EO
*/
template <class EOType>
class eoMonOp: public eoOp<EOType> {
public:
/// Ctor
eoMonOp( )
: eoOp<EOType>( eoOp<EOType>::unary ) {};
/// Copy Ctor
eoMonOp( const eoMonOp& _emop )
: eoOp<EOType>( _emop ){};
/// Dtor
~eoMonOp() {};
/** applies randomly operator, to the object. If arity is more than 1,
* keeps a copy of the operand in a cache.
*/
virtual void operator()( EOType& _eo1) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoMonOp";};
//@}
};
// some forward declarations
template<class EOT>
class eoIndiSelector;
template<class EOT>
class eoInserter;
/**
* eGeneralOp: General genetic operator; for objects used to transform sets
of EOs. Nary ("orgy") operators should be derived from this class
*/
template<class EOT>
class eoGeneralOp: public eoOp<EOT>
{
public:
/// Ctor that honors its superclass
eoGeneralOp(): eoOp<EOT>( eoOp<EOT>::general ) {};
/// Virtual dtor
virtual ~eoGeneralOp () {};
/** Method that really does the stuff. Applies the genetic operator
to a individuals dispensed by an eoIndividualSelector,
and puts the results in the eoIndividualInserter.
Any number of inputs can be requested and any number of outputs
can be produced.
*/
virtual void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const = 0;
virtual string className() const {return "eoGeneralOp";};
};
#endif
// -*- 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 _eoOp_H
#define _eoOp_H
#include <eoObject.h>
#include <eoPrintable.h>
/** @name Genetic operators
What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with
eoOp as father and eoMonOp (monary or unary operator) and eoBinOp and eoQuadraticOp (binary operators)
as siblings). Nobody should subclass eoOp, you should subclass eoGeneralOp, eoBinOp, eoQuadraticOp or eoMonOp,
those are the ones actually used here.\\
#eoOp#s are only printable objects, so if you want to build them from a file, it has to
be done in another class, namely factories. Each hierarchy of #eoOp#s should have its own
factory, which know how to build them from a description in a file.
@author GeNeura Team
@version 0.1
@see eoOpFactory
*/
/** Abstract data types for EO operators.
* Genetic operators act on chromosomes, changing them. The type to instantiate them should
* be an eoObject, but in any case, they are type-specific; each kind of evolvable object
* can have its own operators
*/
template<class EOType>
class eoOp: public eoObject, public eoPrintable {
public:
//@{
enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3};
///
/// Ctor
eoOp(OpType _type)
:opType( _type ) {};
/// Copy Ctor
eoOp( const eoOp& _eop )
:opType( _eop.opType ) {};
/// Needed virtual destructor
virtual ~eoOp(){};
/// getType: number of operands it takes and individuals it produces
OpType getType() const {return opType;};
/** @name Methods from eoObject */
//@{
/**
* Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream.
*/
virtual void printOn(ostream& _os) const {
_os << className().c_str();
// _os << arity;
};
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoOp";};
//@}
private:
/// OpType is the type of the operator: how many operands it takes and how many it produces
OpType opType;
};
/** Binary genetic operator: subclasses eoOp, and defines
basically the operator() with two operands
*/
template<class EOType>
class eoBinOp: public eoOp<EOType> {
public:
/// Ctor
eoBinOp()
:eoOp<EOType>( binary ) {};
/// Copy Ctor
eoBinOp( const eoBinOp& _ebop )
: eoOp<EOType>( _ebop ){};
/// Dtor
~eoBinOp () {};
/** applies operator, to the object. Modifies only the first operand.
*/
virtual void operator()( EOType& _eo1, const EOType& _eo2 ) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoBinOp";};
//@}
};
/** Quadratic genetic operator: subclasses eoOp, and defines
basically the operator() with two operands
*/
template<class EOType>
class eoQuadraticOp: public eoOp<EOType> {
public:
/// Ctor
eoQuadraticOp()
:eoOp<EOType>( eoOp<EOType>::quadratic ) {};
/// Copy Ctor
eoQuadraticOp( const eoQuadraticOp& _ebop )
: eoOp<EOType>( _ebop ){};
/// Dtor
~eoQuadraticOp() {};
/** applies operator, to the object. Modifies both operands.
*/
virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoBinOp";};
//@}
};
/** eoMonOp is the monary operator: genetic operator that takes
only one EO
*/
template <class EOType>
class eoMonOp: public eoOp<EOType> {
public:
/// Ctor
eoMonOp( )
: eoOp<EOType>( eoOp<EOType>::unary ) {};
/// Copy Ctor
eoMonOp( const eoMonOp& _emop )
: eoOp<EOType>( _emop ){};
/// Dtor
~eoMonOp() {};
/** applies randomly operator, to the object. If arity is more than 1,
* keeps a copy of the operand in a cache.
*/
virtual void operator()( EOType& _eo1) const = 0;
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
virtual string className() const {return "eoMonOp";};
//@}
};
// some forward declarations
template<class EOT>
class eoIndiSelector;
template<class EOT>
class eoInserter;
/**
* eGeneralOp: General genetic operator; for objects used to transform sets
of EOs. Nary ("orgy") operators should be derived from this class
*/
template<class EOT>
class eoGeneralOp: public eoOp<EOT>
{
public:
/// Ctor that honors its superclass
eoGeneralOp(): eoOp<EOT>( eoOp<EOT>::general ) {};
/// Virtual dtor
virtual ~eoGeneralOp () {};
/** Method that really does the stuff. Applies the genetic operator
to a individuals dispensed by an eoIndividualSelector,
and puts the results in the eoIndividualInserter.
Any number of inputs can be requested and any number of outputs
can be produced.
*/
virtual void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const = 0;
virtual string className() const {return "eoGeneralOp";};
};
#endif

View file

@ -1,14 +1,15 @@
#include <eoPersistent.h>
//Implementation of these objects
//-----------------------------------------------------------------------------
istream & operator >> ( istream& _is, eoPersistent& _o ) {
_o.readFrom(_is);
return _is;
};
#include "eoRNG.h"
eoRng rng;
#include <eoPersistent.h>
//Implementation of these objects
//-----------------------------------------------------------------------------
istream & operator >> ( istream& _is, eoPersistent& _o ) {
_o.readFrom(_is);
return _is;
};
#include "eoRNG.h"
eoRng rng;

View file

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

View file

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

View file

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

View file

@ -1,40 +1,45 @@
//-----------------------------------------------------------------------------
// eoProblem.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 EOPROBLEM_H
#define EOPROBLEM_H
//-----------------------------------------------------------------------------
template<class T> class Problem
{
public:
typedef T Chrom;
typedef typename T::Gene Gene;
typedef typename T::Fitness Fitness;
virtual Fitness operator()(const Chrom& chrom) = 0;
};
//-----------------------------------------------------------------------------
#endif EOPROBLEM_H
//-----------------------------------------------------------------------------
// eoProblem.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 EOPROBLEM_H
#define EOPROBLEM_H
//-----------------------------------------------------------------------------
template<class T> class Problem
{
public:
typedef T Chrom;
typedef typename T::Gene Gene;
typedef typename T::Fitness Fitness;
virtual Fitness operator()(const Chrom& chrom) = 0;
};
//-----------------------------------------------------------------------------
#endif EOPROBLEM_H

View file

@ -1,54 +1,55 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoProportionalGOpSelector.h
Proportional Generalized Operator Selector.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com), 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 eoProportionalGOpSelector_h
#define eoProportionalGOpSelector_h
//-----------------------------------------------------------------------------
#include "eoGOpSelector.h"
/** eoProportionalGOpSel: do proportional selection, returns one of the
operators
*/
template <class EOT>
class eoProportionalGOpSel : public eoGOpSelector<EOT>
{
public :
eoProportionalGOpSel() : eoGOpSelector<EOT>() {}
/** Returns the operator proportionally selected */
virtual eoGeneralOp<EOT>& selectOp()
{
unsigned what = rng.roulette_wheel(getRates());
return *operator[](what);
}
///
virtual string className() const { return "eoGOpSelector"; };
};
#endif
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoProportionalGOpSelector.h
Proportional Generalized Operator Selector.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com), 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 eoProportionalGOpSelector_h
#define eoProportionalGOpSelector_h
//-----------------------------------------------------------------------------
#include "eoGOpSelector.h"
/** eoProportionalGOpSel: do proportional selection, returns one of the
operators
*/
template <class EOT>
class eoProportionalGOpSel : public eoGOpSelector<EOT>
{
public :
eoProportionalGOpSel() : eoGOpSelector<EOT>() {}
/** Returns the operator proportionally selected */
virtual eoGeneralOp<EOT>& selectOp()
{
unsigned what = rng.roulette_wheel(getRates());
return *operator[](what);
}
///
virtual string className() const { return "eoGOpSelector"; };
};
#endif

View file

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

View file

@ -1,452 +1,453 @@
/*
* Random number generator adapted from (see comments below)
*
* The random number generator is modified into a class
* by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller
* transformation to generate normal deviates.
*
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
*/
/* ************ DOCUMENTATION IN ORIGINAL FILE *********************/
// This is the ``Mersenne Twister'' random number generator MT19937, which
// generates pseudorandom integers uniformly distributed in 0..(2^32 - 1)
// starting from any odd seed in 0..(2^32 - 1). This version is a recode
// by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by
// Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in
// July-August 1997).
//
// Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha
// running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to
// generate 300 million random numbers; after recoding: 24.0 sec. for the same
// (i.e., 46.5% of original time), so speed is now about 12.5 million random
// number generations per second on this machine.
//
// According to the URL <http://www.math.keio.ac.jp/~matumoto/emt.html>
// (and paraphrasing a bit in places), the Mersenne Twister is ``designed
// with consideration of the flaws of various existing generators,'' has
// a period of 2^19937 - 1, gives a sequence that is 623-dimensionally
// equidistributed, and ``has passed many stringent tests, including the
// die-hard test of G. Marsaglia and the load test of P. Hellekalek and
// S. Wegenkittl.'' It is efficient in memory usage (typically using 2506
// to 5012 bytes of static data, depending on data type sizes, and the code
// is quite short as well). It generates random numbers in batches of 624
// at a time, so the caching and pipelining of modern systems is exploited.
// It is also divide- and mod-free.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Library 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 Library General Public License for more details. You should have
// received a copy of the GNU Library 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.
//
// The code as Shawn received it included the following notice:
//
// Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When
// you use this, send an e-mail to <matumoto@math.keio.ac.jp> with
// an appropriate reference to your work.
//
// It would be nice to CC: <Cokus@math.washington.edu> when you write.
//
//
// uint32 must be an unsigned integer type capable of holding at least 32
// bits; exactly 32 should be fastest, but 64 is better on an Alpha with
// GCC at -O3 optimization so try your options and see what's best for you
//
/* ************ END DOCUMENTATION IN ORIGINAL FILE *********************/
#ifndef EO_RANDOM_NUMBER_GENERATOR
#define EO_RANDOM_NUMBER_GENERATOR
#include <ctime>
#include <eoPersistent.h>
#include <eoObject.h>
// TODO: check for various compilers if this is exactly 32 bits
// Unfortunately MSVC's preprocessor does not comprehends sizeof()
// so neat preprocessing tricks will not work
typedef unsigned long uint32; // Compiler and platform dependent!
//-----------------------------------------------------------------------------
// eoRng
//-----------------------------------------------------------------------------
/**
eoRng is a persitent class that uses the ``Mersenne Twister'' random number generator MT19937
for generating random numbers. The various member functions implement useful functions
for evolutionary algorithms. Included are: rand(), random(), flip() and normal().
Note for people porting EO to other platforms: please make sure that the typedef
uint32 in the file eoRng.h is exactly 32 bits long. It may be longer, but not
shorter. If it is longer, file compatibility between EO on different platforms
may be broken.
*/
class eoRng : public eoObject, public eoPersistent
{
public :
/**
ctor takes a random seed; if you want another seed, use reseed
@see reseed
*/
eoRng(uint32 s = (uint32) time(0) ) : state(0), next(0), left(-1), cached(false), N(624), M(397), K(0x9908B0DFU) {
state = new uint32[N+1];
initialize(s);
}
~eoRng(void)
{
delete [] state;
}
/**
Re-initializes the Random Number Generator.
*/
void reseed(uint32 s)
{
initialize(s);
}
/**
uniform(m = 1.0) returns a random double in the range [0, m)
*/
double uniform(double m = 1.0)
{ // random number between [0, m]
return m * double(rand()) / double(rand_max());
}
/**
random() returns a random integer in the range [0, m)
*/
uint32 random(uint32 m)
{
return uint32(uniform() * double(m));
}
/**
flip() tosses a biased coin such that flip(x/100.0) will
returns true x% of the time
*/
bool flip(float bias)
{
return uniform() < bias;
}
/**
normal() zero mean gaussian deviate with standard deviation of 1
*/
double normal(void); // gaussian mutation, stdev 1
/**
normal(stdev) zero mean gaussian deviate with user defined standard deviation
*/
double normal(double stdev)
{
return stdev * normal();
}
/**
normal(mean, stdev) user defined mean gaussian deviate with user defined standard deviation
*/
double normal(double mean, double stdev)
{
return mean + normal(stdev);
}
/**
rand() returns a random number in the range [0, rand_max)
*/
uint32 rand();
/**
rand_max() the maximum returned by rand()
*/
uint32 rand_max(void) const { return (uint32) 0xffffffff; }
/**
roulette_wheel(vec, total = 0) does a roulette wheel selection
on the input vector vec. If the total is not supplied, it is
calculated. It returns an integer denoting the selected argument.
*/
template <class T>
int roulette_wheel(const std::vector<T>& vec, T total = 0)
{
if (total == 0)
{ // count
for (int i = 0; i < vec.size(); ++i)
total += vec[i];
}
float change = uniform() * total;
int i = 0;
while (change > 0)
{
change -= vec[i++];
}
return --i;
}
///
void printOn(ostream& _os) const
{
for (int i = 0; i < N; ++i)
{
_os << state[i] << ' ';
}
_os << int(next - state) << ' ';
_os << left << ' ' << cached << ' ' << cacheValue;
}
///
void readFrom(istream& _is)
{
for (int i = 0; i < N; ++i)
{
_is >> state[i];
}
int n;
_is >> n;
next = state + n;
_is >> left;
_is >> cached;
_is >> cacheValue;
}
private :
uint32 restart(void);
void initialize(uint32 seed);
uint32* state; // the array for the state
uint32* next;
int left;
bool cached;
float cacheValue;
const int N;
const int M;
const uint32 K; // a magic constant
/**
Private copy ctor and assignment operator to make sure that
nobody accidentally copies the random number generator.
If you want similar RNG's, make two RNG's and initialize
them with the same seed.
*/
eoRng (const eoRng&); // no implementation
eoRng& operator=(const eoRng&); // dito
};
/**
The one and only global eoRng object
*/
extern eoRng rng;
/**
The class uniform_generator can be used in the STL generate function
to easily generate random floats and doubles between [0, _max). _max
defaults to 1.0
*/
template <class T = double> class uniform_generator
{
public :
uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {}
virtual T operator()(void) { return (T) uniform.uniform(maxim); }
private :
T maxim;
eoRng& uniform;
};
/**
The class random_generator can be used in the STL generate function
to easily generate random ints between [0, _max).
*/
template <class T = uint32> class random_generator
{
public :
random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {}
virtual T operator()(void) { return (T) random.random(max); }
private :
T maxim;
eoRng& random;
};
/**
The class normal_generator can be used in the STL generate function
to easily generate gaussian distributed floats and doubles. The user
can supply a standard deviation which defaults to 1.
*/
template <class T = double> class normal_generator
{
public :
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
virtual T operator()(void) { return (T) normal.normal(stdev); }
private :
T stdev;
eoRng& normal;
};
// Implementation of some eoRng members.... Don't mind the mess, it does work.
#define hiBit(u) ((u) & 0x80000000U) // mask all but highest bit of u
#define loBit(u) ((u) & 0x00000001U) // mask all but lowest bit of u
#define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u
#define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v
inline void eoRng::initialize(uint32 seed)
{
//
// We initialize state[0..(N-1)] via the generator
//
// x_new = (69069 * x_old) mod 2^32
//
// from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's
// _The Art of Computer Programming_, Volume 2, 3rd ed.
//
// Notes (SJC): I do not know what the initial state requirements
// of the Mersenne Twister are, but it seems this seeding generator
// could be better. It achieves the maximum period for its modulus
// (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if
// x_initial can be even, you have sequences like 0, 0, 0, ...;
// 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31,
// 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below.
//
// Even if x_initial is odd, if x_initial is 1 mod 4 then
//
// the lowest bit of x is always 1,
// the next-to-lowest bit of x is always 0,
// the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... ,
// the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... ,
// the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... ,
// ...
//
// and if x_initial is 3 mod 4 then
//
// the lowest bit of x is always 1,
// the next-to-lowest bit of x is always 1,
// the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... ,
// the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... ,
// the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... ,
// ...
//
// The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is
// 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It
// also does well in the dimension 2..5 spectral tests, but it could be
// better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth).
//
// Note that the random number user does not see the values generated
// here directly since restart() will always munge them first, so maybe
// none of all of this matters. In fact, the seed values made here could
// even be extra-special desirable if the Mersenne Twister theory says
// so-- that's why the only change I made is to restrict to odd seeds.
//
left = -1;
register uint32 x = (seed | 1U) & 0xFFFFFFFFU, *s = state;
register int j;
for(left=0, *s++=x, j=N; --j;
*s++ = (x*=69069U) & 0xFFFFFFFFU);
}
inline uint32 eoRng::restart(void)
{
register uint32 *p0=state, *p2=state+2, *pM=state+M, s0, s1;
register int j;
left=N-1, next=state+1;
for(s0=state[0], s1=state[1], j=N-M+1; --j; s0=s1, s1=*p2++)
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
for(pM=state, j=M; --j; s0=s1, s1=*p2++)
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
s1=state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
s1 ^= (s1 >> 11);
s1 ^= (s1 << 7) & 0x9D2C5680U;
s1 ^= (s1 << 15) & 0xEFC60000U;
return(s1 ^ (s1 >> 18));
}
inline uint32 eoRng::rand(void)
{
uint32 y;
if(--left < 0)
return(restart());
y = *next++;
y ^= (y >> 11);
y ^= (y << 7) & 0x9D2C5680U;
y ^= (y << 15) & 0xEFC60000U;
return(y ^ (y >> 18));
}
inline double eoRng::normal(void)
{
if (cached)
{
cached = false;
return cacheValue;
}
float rSquare, factor, var1, var2;
do
{
var1 = 2.0 * uniform() - 1.0;
var2 = 2.0 * uniform() - 1.0;
rSquare = var1 * var1 + var2 * var2;
}
while (rSquare >= 1.0 || rSquare == 0.0);
factor = sqrt(-2.0 * log(rSquare) / rSquare);
cacheValue = var1 * factor;
cached = true;
return (var2 * factor);
}
#endif
/*
* Random number generator adapted from (see comments below)
*
* The random number generator is modified into a class
* by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller
* transformation to generate normal deviates.
*
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
*/
/* ************ DOCUMENTATION IN ORIGINAL FILE *********************/
// This is the ``Mersenne Twister'' random number generator MT19937, which
// generates pseudorandom integers uniformly distributed in 0..(2^32 - 1)
// starting from any odd seed in 0..(2^32 - 1). This version is a recode
// by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by
// Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in
// July-August 1997).
//
// Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha
// running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to
// generate 300 million random numbers; after recoding: 24.0 sec. for the same
// (i.e., 46.5% of original time), so speed is now about 12.5 million random
// number generations per second on this machine.
//
// According to the URL <http://www.math.keio.ac.jp/~matumoto/emt.html>
// (and paraphrasing a bit in places), the Mersenne Twister is ``designed
// with consideration of the flaws of various existing generators,'' has
// a period of 2^19937 - 1, gives a sequence that is 623-dimensionally
// equidistributed, and ``has passed many stringent tests, including the
// die-hard test of G. Marsaglia and the load test of P. Hellekalek and
// S. Wegenkittl.'' It is efficient in memory usage (typically using 2506
// to 5012 bytes of static data, depending on data type sizes, and the code
// is quite short as well). It generates random numbers in batches of 624
// at a time, so the caching and pipelining of modern systems is exploited.
// It is also divide- and mod-free.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Library 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 Library General Public License for more details. You should have
// received a copy of the GNU Library 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.
//
// The code as Shawn received it included the following notice:
//
// Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When
// you use this, send an e-mail to <matumoto@math.keio.ac.jp> with
// an appropriate reference to your work.
//
// It would be nice to CC: <Cokus@math.washington.edu> when you write.
//
//
// uint32 must be an unsigned integer type capable of holding at least 32
// bits; exactly 32 should be fastest, but 64 is better on an Alpha with
// GCC at -O3 optimization so try your options and see what's best for you
//
/* ************ END DOCUMENTATION IN ORIGINAL FILE *********************/
#ifndef EO_RANDOM_NUMBER_GENERATOR
#define EO_RANDOM_NUMBER_GENERATOR
#include <ctime>
#include <eoPersistent.h>
#include <eoObject.h>
// TODO: check for various compilers if this is exactly 32 bits
// Unfortunately MSVC's preprocessor does not comprehends sizeof()
// so neat preprocessing tricks will not work
typedef unsigned long uint32; // Compiler and platform dependent!
//-----------------------------------------------------------------------------
// eoRng
//-----------------------------------------------------------------------------
/**
eoRng is a persitent class that uses the ``Mersenne Twister'' random number generator MT19937
for generating random numbers. The various member functions implement useful functions
for evolutionary algorithms. Included are: rand(), random(), flip() and normal().
Note for people porting EO to other platforms: please make sure that the typedef
uint32 in the file eoRng.h is exactly 32 bits long. It may be longer, but not
shorter. If it is longer, file compatibility between EO on different platforms
may be broken.
*/
class eoRng : public eoObject, public eoPersistent
{
public :
/**
ctor takes a random seed; if you want another seed, use reseed
@see reseed
*/
eoRng(uint32 s = (uint32) time(0) ) : state(0), next(0), left(-1), cached(false), N(624), M(397), K(0x9908B0DFU) {
state = new uint32[N+1];
initialize(s);
}
~eoRng(void)
{
delete [] state;
}
/**
Re-initializes the Random Number Generator.
*/
void reseed(uint32 s)
{
initialize(s);
}
/**
uniform(m = 1.0) returns a random double in the range [0, m)
*/
double uniform(double m = 1.0)
{ // random number between [0, m]
return m * double(rand()) / double(rand_max());
}
/**
random() returns a random integer in the range [0, m)
*/
uint32 random(uint32 m)
{
return uint32(uniform() * double(m));
}
/**
flip() tosses a biased coin such that flip(x/100.0) will
returns true x% of the time
*/
bool flip(float bias)
{
return uniform() < bias;
}
/**
normal() zero mean gaussian deviate with standard deviation of 1
*/
double normal(void); // gaussian mutation, stdev 1
/**
normal(stdev) zero mean gaussian deviate with user defined standard deviation
*/
double normal(double stdev)
{
return stdev * normal();
}
/**
normal(mean, stdev) user defined mean gaussian deviate with user defined standard deviation
*/
double normal(double mean, double stdev)
{
return mean + normal(stdev);
}
/**
rand() returns a random number in the range [0, rand_max)
*/
uint32 rand();
/**
rand_max() the maximum returned by rand()
*/
uint32 rand_max(void) const { return (uint32) 0xffffffff; }
/**
roulette_wheel(vec, total = 0) does a roulette wheel selection
on the input vector vec. If the total is not supplied, it is
calculated. It returns an integer denoting the selected argument.
*/
template <class T>
int roulette_wheel(const std::vector<T>& vec, T total = 0)
{
if (total == 0)
{ // count
for (int i = 0; i < vec.size(); ++i)
total += vec[i];
}
float change = uniform() * total;
int i = 0;
while (change > 0)
{
change -= vec[i++];
}
return --i;
}
///
void printOn(ostream& _os) const
{
for (int i = 0; i < N; ++i)
{
_os << state[i] << ' ';
}
_os << int(next - state) << ' ';
_os << left << ' ' << cached << ' ' << cacheValue;
}
///
void readFrom(istream& _is)
{
for (int i = 0; i < N; ++i)
{
_is >> state[i];
}
int n;
_is >> n;
next = state + n;
_is >> left;
_is >> cached;
_is >> cacheValue;
}
private :
uint32 restart(void);
void initialize(uint32 seed);
uint32* state; // the array for the state
uint32* next;
int left;
bool cached;
float cacheValue;
const int N;
const int M;
const uint32 K; // a magic constant
/**
Private copy ctor and assignment operator to make sure that
nobody accidentally copies the random number generator.
If you want similar RNG's, make two RNG's and initialize
them with the same seed.
*/
eoRng (const eoRng&); // no implementation
eoRng& operator=(const eoRng&); // dito
};
/**
The one and only global eoRng object
*/
extern eoRng rng;
/**
The class uniform_generator can be used in the STL generate function
to easily generate random floats and doubles between [0, _max). _max
defaults to 1.0
*/
template <class T = double> class uniform_generator
{
public :
uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {}
virtual T operator()(void) { return (T) uniform.uniform(maxim); }
private :
T maxim;
eoRng& uniform;
};
/**
The class random_generator can be used in the STL generate function
to easily generate random ints between [0, _max).
*/
template <class T = uint32> class random_generator
{
public :
random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {}
virtual T operator()(void) { return (T) random.random(max); }
private :
T maxim;
eoRng& random;
};
/**
The class normal_generator can be used in the STL generate function
to easily generate gaussian distributed floats and doubles. The user
can supply a standard deviation which defaults to 1.
*/
template <class T = double> class normal_generator
{
public :
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
virtual T operator()(void) { return (T) normal.normal(stdev); }
private :
T stdev;
eoRng& normal;
};
// Implementation of some eoRng members.... Don't mind the mess, it does work.
#define hiBit(u) ((u) & 0x80000000U) // mask all but highest bit of u
#define loBit(u) ((u) & 0x00000001U) // mask all but lowest bit of u
#define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u
#define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v
inline void eoRng::initialize(uint32 seed)
{
//
// We initialize state[0..(N-1)] via the generator
//
// x_new = (69069 * x_old) mod 2^32
//
// from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's
// _The Art of Computer Programming_, Volume 2, 3rd ed.
//
// Notes (SJC): I do not know what the initial state requirements
// of the Mersenne Twister are, but it seems this seeding generator
// could be better. It achieves the maximum period for its modulus
// (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if
// x_initial can be even, you have sequences like 0, 0, 0, ...;
// 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31,
// 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below.
//
// Even if x_initial is odd, if x_initial is 1 mod 4 then
//
// the lowest bit of x is always 1,
// the next-to-lowest bit of x is always 0,
// the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... ,
// the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... ,
// the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... ,
// ...
//
// and if x_initial is 3 mod 4 then
//
// the lowest bit of x is always 1,
// the next-to-lowest bit of x is always 1,
// the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... ,
// the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... ,
// the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... ,
// ...
//
// The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is
// 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It
// also does well in the dimension 2..5 spectral tests, but it could be
// better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth).
//
// Note that the random number user does not see the values generated
// here directly since restart() will always munge them first, so maybe
// none of all of this matters. In fact, the seed values made here could
// even be extra-special desirable if the Mersenne Twister theory says
// so-- that's why the only change I made is to restrict to odd seeds.
//
left = -1;
register uint32 x = (seed | 1U) & 0xFFFFFFFFU, *s = state;
register int j;
for(left=0, *s++=x, j=N; --j;
*s++ = (x*=69069U) & 0xFFFFFFFFU);
}
inline uint32 eoRng::restart(void)
{
register uint32 *p0=state, *p2=state+2, *pM=state+M, s0, s1;
register int j;
left=N-1, next=state+1;
for(s0=state[0], s1=state[1], j=N-M+1; --j; s0=s1, s1=*p2++)
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
for(pM=state, j=M; --j; s0=s1, s1=*p2++)
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
s1=state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
s1 ^= (s1 >> 11);
s1 ^= (s1 << 7) & 0x9D2C5680U;
s1 ^= (s1 << 15) & 0xEFC60000U;
return(s1 ^ (s1 >> 18));
}
inline uint32 eoRng::rand(void)
{
uint32 y;
if(--left < 0)
return(restart());
y = *next++;
y ^= (y >> 11);
y ^= (y << 7) & 0x9D2C5680U;
y ^= (y << 15) & 0xEFC60000U;
return(y ^ (y >> 18));
}
inline double eoRng::normal(void)
{
if (cached)
{
cached = false;
return cacheValue;
}
float rSquare, factor, var1, var2;
do
{
var1 = 2.0 * uniform() - 1.0;
var2 = 2.0 * uniform() - 1.0;
rSquare = var1 * var1 + var2 * var2;
}
while (rSquare >= 1.0 || rSquare == 0.0);
factor = sqrt(-2.0 * log(rSquare) / rSquare);
cacheValue = var1 * factor;
cached = true;
return (var2 * factor);
}
#endif

View file

@ -1,51 +1,52 @@
/* -*- 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"
/**
* 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
/* -*- 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"
/**
* 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

@ -1,61 +1,62 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoSequentialGOpSelector.h
Sequential Generalized Operator Selector.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com), 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 eoSequentialGOpSelector_h
#define eoSequentialGOpSelector_h
//-----------------------------------------------------------------------------
#include "eoGOpSelector.h"
/** eoSequentialGOpSel: do proportional selection, but return a sequence of
operations to be applied one after the other.
*/
template <class EOT>
class eoSequentialGOpSel : public eoGOpSelector<EOT>
{
public :
virtual eoGeneralOp<EOT>& selectOp()
{
combined.clear();
for (int i = 0; i < size(); ++i)
{
if (operator[](i) == 0)
continue;
if (rng.flip(getRates()[i]))
combined.addOp(operator[](i));
}
return combined;
}
private :
eoCombinedOp<EOT> combined;
};
#endif
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoSequentialGOpSelector.h
Sequential Generalized Operator Selector.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com), 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 eoSequentialGOpSelector_h
#define eoSequentialGOpSelector_h
//-----------------------------------------------------------------------------
#include "eoGOpSelector.h"
/** eoSequentialGOpSel: do proportional selection, but return a sequence of
operations to be applied one after the other.
*/
template <class EOT>
class eoSequentialGOpSel : public eoGOpSelector<EOT>
{
public :
virtual eoGeneralOp<EOT>& selectOp()
{
combined.clear();
for (int i = 0; i < size(); ++i)
{
if (operator[](i) == 0)
continue;
if (rng.flip(getRates()[i]))
combined.addOp(operator[](i));
}
return combined;
}
private :
eoCombinedOp<EOT> combined;
};
#endif

View file

@ -1,86 +1,87 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoSteadyStateEA.h
// (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 _eoSteadyStateEA_h
#define _eoSteadyStateEA_h
//-----------------------------------------------------------------------------
#include "eoSteadyStateGeneration.h" // eoPop
#include <eoTerm.h>
/** EOSteadyStateEA:
An easy-to-use evolutionary algorithm, just supply
a general operator selector, a selector for choosing the ones
to reproduce and an eoSteadyStateInserter that takes care of evaluating
and inserter the guy/girl in the steady state population.
*/
template<class EOT> class eoSteadyStateEA: public eoAlgo<EOT>
{
public:
/// Constructor.
eoSteadyStateEA(
eoGOpSelector<EOT>& _opSelector,
eoPopIndiSelector<EOT>& _selector,
eoSteadyStateInserter<EOT>& _inserter,
eoTerm<EOT>& _terminator,
unsigned _steps = 0 )
: step(_opSelector, _selector, _inserter),
terminator( _terminator)
{};
/// Constructor from an already created generation
eoSteadyStateEA(eoSteadyStateGeneration<EOT>& _gen,
eoTerm<EOT>& _terminator):
step(_gen),
terminator( _terminator){};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop) {
do {
try
{
step(pop);
}
catch (exception& e)
{
string s = e.what();
s.append( " in eoSteadyStateEA ");
throw runtime_error( s );
}
} while ( terminator( pop ) );
}
/// Class name.
string className() const { return "eoSteadyStateEA"; }
private:
eoSteadyStateGeneration<EOT> step;
eoTerm<EOT>& terminator;
};
//-----------------------------------------------------------------------------
#endif eoEasyEA_h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoSteadyStateEA.h
// (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 _eoSteadyStateEA_h
#define _eoSteadyStateEA_h
//-----------------------------------------------------------------------------
#include "eoSteadyStateGeneration.h" // eoPop
#include <eoTerm.h>
/** EOSteadyStateEA:
An easy-to-use evolutionary algorithm, just supply
a general operator selector, a selector for choosing the ones
to reproduce and an eoSteadyStateInserter that takes care of evaluating
and inserter the guy/girl in the steady state population.
*/
template<class EOT> class eoSteadyStateEA: public eoAlgo<EOT>
{
public:
/// Constructor.
eoSteadyStateEA(
eoGOpSelector<EOT>& _opSelector,
eoPopIndiSelector<EOT>& _selector,
eoSteadyStateInserter<EOT>& _inserter,
eoTerm<EOT>& _terminator,
unsigned _steps = 0 )
: step(_opSelector, _selector, _inserter),
terminator( _terminator)
{};
/// Constructor from an already created generation
eoSteadyStateEA(eoSteadyStateGeneration<EOT>& _gen,
eoTerm<EOT>& _terminator):
step(_gen),
terminator( _terminator){};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop) {
do {
try
{
step(pop);
}
catch (exception& e)
{
string s = e.what();
s.append( " in eoSteadyStateEA ");
throw runtime_error( s );
}
} while ( terminator( pop ) );
}
/// Class name.
string className() const { return "eoSteadyStateEA"; }
private:
eoSteadyStateGeneration<EOT> step;
eoTerm<EOT>& terminator;
};
//-----------------------------------------------------------------------------
#endif eoEasyEA_h

View file

@ -1,88 +1,89 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoSteadyStateGeneration.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 eoSteadyStateGeneration_h
#define eoSteadyStateGeneration_h
//-----------------------------------------------------------------------------
#include <eoAlgo.h> // eoPop
#include <eoEvalFunc.h>
#include <eoPopOps.h> // eoSelect, eoTranform, eoMerge
#include "eoGOpSelector.h"
#include "eoIndiSelector.h"
#include "eoSteadyStateInserter.h"
//-----------------------------------------------------------------------------
/** eoSteadyStateGeneration
* Single step of a steady state evolutionary algorithm.
* Proceeds by updating one individual at a time, by first selecting parents,
* creating one or more children and subsequently overwrite (a) bad individual(s)
*/
template<class EOT> class eoSteadyStateGeneration: public eoAlgo<EOT>
{
public:
/// Constructor.
eoSteadyStateGeneration(
eoGOpSelector<EOT>& _opSelector,
eoPopIndiSelector<EOT>& _selector,
eoSteadyStateInserter<EOT>& _inserter,
unsigned _steps = 0) :
opSelector(_opSelector),
selector(_selector),
inserter(_inserter) ,
steps(_steps) {};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop)
{
unsigned nSteps = steps;
if (nSteps == 0)
{
nSteps = pop.size(); // make a 'generation equivalent'
}
for (unsigned i = 0; i < nSteps; ++i)
{
opSelector.selectOp()(selector(pop), inserter(pop));
}
}
/// Class name.
string className() const { return "eoSteadyStateGeneration"; }
private:
eoGOpSelector<EOT>& opSelector;
eoPopIndiSelector<EOT>& selector;
eoSteadyStateInserter<EOT>& inserter;
unsigned steps;
};
//-----------------------------------------------------------------------------
#endif eoGeneration_h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoSteadyStateGeneration.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 eoSteadyStateGeneration_h
#define eoSteadyStateGeneration_h
//-----------------------------------------------------------------------------
#include <eoAlgo.h> // eoPop
#include <eoEvalFunc.h>
#include <eoPopOps.h> // eoSelect, eoTranform, eoMerge
#include "eoGOpSelector.h"
#include "eoIndiSelector.h"
#include "eoSteadyStateInserter.h"
//-----------------------------------------------------------------------------
/** eoSteadyStateGeneration
* Single step of a steady state evolutionary algorithm.
* Proceeds by updating one individual at a time, by first selecting parents,
* creating one or more children and subsequently overwrite (a) bad individual(s)
*/
template<class EOT> class eoSteadyStateGeneration: public eoAlgo<EOT>
{
public:
/// Constructor.
eoSteadyStateGeneration(
eoGOpSelector<EOT>& _opSelector,
eoPopIndiSelector<EOT>& _selector,
eoSteadyStateInserter<EOT>& _inserter,
unsigned _steps = 0) :
opSelector(_opSelector),
selector(_selector),
inserter(_inserter) ,
steps(_steps) {};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop)
{
unsigned nSteps = steps;
if (nSteps == 0)
{
nSteps = pop.size(); // make a 'generation equivalent'
}
for (unsigned i = 0; i < nSteps; ++i)
{
opSelector.selectOp()(selector(pop), inserter(pop));
}
}
/// Class name.
string className() const { return "eoSteadyStateGeneration"; }
private:
eoGOpSelector<EOT>& opSelector;
eoPopIndiSelector<EOT>& selector;
eoSteadyStateInserter<EOT>& inserter;
unsigned steps;
};
//-----------------------------------------------------------------------------
#endif eoGeneration_h

View file

@ -1,51 +1,51 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoSteadyStateInserter.h
Still abstract population insertion operator that is initialized with
and eoEvalFunc object to be able to evaluate individuals before inserting
them.
(c) Maarten Keijzer (mak@dhi.dk) 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 eoSteadyStateInserter_h
#define eoSteadyStateInserter_h
#include "eoEvalFunc.h"
/**
* eoSteadyStateInserter: Interface class that enables an operator to update
* a population with a new individual... it contains an eoEvalFunc object to
* make sure that every individual is evaluated before it is inserted
*/
template <class EOT>
class eoSteadyStateInserter : public eoPopInserter<EOT>
{
public :
eoSteadyStateInserter(eoEvalFunc<EOT>& _eval) : eval(_eval) , eoPopInserter<EOT>() {}
protected :
eoEvalFunc<EOT>& eval;
};
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoSteadyStateInserter.h
Still abstract population insertion operator that is initialized with
and eoEvalFunc object to be able to evaluate individuals before inserting
them.
(c) Maarten Keijzer (mak@dhi.dk) 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 eoSteadyStateInserter_h
#define eoSteadyStateInserter_h
#include "eoEvalFunc.h"
/**
* eoSteadyStateInserter: Interface class that enables an operator to update
* a population with a new individual... it contains an eoEvalFunc object to
* make sure that every individual is evaluated before it is inserted
*/
template <class EOT>
class eoSteadyStateInserter : public eoPopInserter<EOT>
{
public :
eoSteadyStateInserter(eoEvalFunc<EOT>& _eval) : eval(_eval) , eoPopInserter<EOT>() {}
protected :
eoEvalFunc<EOT>& eval;
};
#endif

View file

@ -1,68 +1,69 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoStochTournament.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 eoStochTournament_h
#define eoStochTournament_h
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h>
//-----------------------------------------------------------------------------
/** eoStochTournament: a selection method that selects ONE individual by
binary stochastic tournament
-MS- 24/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoStochTournament: public eoSelectOne<EOT>
{
public:
///
eoStochTournament(float _Trate = 1.0 ):eoSelectOne<EOT>(), Trate(_Trate) {
// consistency check
if (Trate < 0.5) {
cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n";
Trate = 0.55;
}
}
/** DANGER: if you want to be able to minimize as well as maximizem
DON'T cast the fitness to a float, use the EOT comparator! */
virtual const EOT& operator()(const eoPop<EOT>& pop)
{
return stochastic_tournament(pop, Trate)();
}
private:
float Trate;
};
//-----------------------------------------------------------------------------
#endif eoDetTournament_h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoStochTournament.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 eoStochTournament_h
#define eoStochTournament_h
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h>
//-----------------------------------------------------------------------------
/** eoStochTournament: a selection method that selects ONE individual by
binary stochastic tournament
-MS- 24/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoStochTournament: public eoSelectOne<EOT>
{
public:
///
eoStochTournament(float _Trate = 1.0 ):eoSelectOne<EOT>(), Trate(_Trate) {
// consistency check
if (Trate < 0.5) {
cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n";
Trate = 0.55;
}
}
/** DANGER: if you want to be able to minimize as well as maximizem
DON'T cast the fitness to a float, use the EOT comparator! */
virtual const EOT& operator()(const eoPop<EOT>& pop)
{
return stochastic_tournament(pop, Trate)();
}
private:
float Trate;
};
//-----------------------------------------------------------------------------
#endif eoDetTournament_h

View file

@ -1,73 +1,73 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoStochTournamentInserter.h
Concrete steady state inserter. It is initialized with a population and
inserts individuals in the population based on an inverse stochastic
tournament
(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 eoStochTournamentInserter_h
#define eoStochTournamentInserter_h
#include "eoSteadyStateInserter.h"
#include "selectors.h"
/**
* eoDetTournamentInserter: Uses an inverse stochastic tournament to figure
* out who gets overridden by the new individual. It resets the fitness of the
* individual.
*/
template <class EOT>
class eoStochTournamentInserter : public eoSteadyStateInserter<EOT>
{
public :
eoStochTournamentInserter(eoEvalFunc<EOT>& _eval, double _t_rate) : t_rate(_t_rate), eoSteadyStateInserter<EOT>(_eval)
{
if (t_rate < 0.5)
{ // warning, error?
t_rate = 0.55;
}
if (t_rate >= 1.0)
{
t_rate = 0.99; // 1.0 would mean deterministic tournament
}
}
void insert(const EOT& _eot)
{
EOT& eo = inverse_stochastic_tournament<EOT>(pop(), t_rate);
eo = _eot; // overwrite loser of tournament
eo.invalidate();
eval(eo); // Evaluate after insert
}
string className(void) const { return "eoStochTournamentInserter"; }
private :
double t_rate;
};
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoStochTournamentInserter.h
Concrete steady state inserter. It is initialized with a population and
inserts individuals in the population based on an inverse stochastic
tournament
(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 eoStochTournamentInserter_h
#define eoStochTournamentInserter_h
#include "eoSteadyStateInserter.h"
#include "selectors.h"
/**
* eoDetTournamentInserter: Uses an inverse stochastic tournament to figure
* out who gets overridden by the new individual. It resets the fitness of the
* individual.
*/
template <class EOT>
class eoStochTournamentInserter : public eoSteadyStateInserter<EOT>
{
public :
eoStochTournamentInserter(eoEvalFunc<EOT>& _eval, double _t_rate) : t_rate(_t_rate), eoSteadyStateInserter<EOT>(_eval)
{
if (t_rate < 0.5)
{ // warning, error?
t_rate = 0.55;
}
if (t_rate >= 1.0)
{
t_rate = 0.99; // 1.0 would mean deterministic tournament
}
}
void insert(const EOT& _eot)
{
EOT& eo = inverse_stochastic_tournament<EOT>(pop(), t_rate);
eo = _eot; // overwrite loser of tournament
eo.invalidate();
eval(eo); // Evaluate after insert
}
string className(void) const { return "eoStochTournamentInserter"; }
private :
double t_rate;
};
#endif

View file

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

View file

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

View file

@ -1,64 +1,65 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoUniformSelect.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 eoUniformSelect_h
#define eoUniformSelect_h
// WARNING: 2 classes in this one - eoUniformSelect and eoCopySelect
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h>
//-----------------------------------------------------------------------------
/** eoUniformSelect: a selection method that selects ONE individual randomly
-MS- 22/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoUniformSelect: public eoSelectOne<EOT>
{
public:
/// (Default) Constructor.
eoUniformSelect():eoSelectOne<EOT>() {}
/// not a big deal!!!
virtual const EOT& operator()(const eoPop<EOT>& pop) {
return pop[rng.random(pop.size())] ;
}
/// Methods inherited from eoObject
//@{
/** Return the class id.
* @return the class name as a string
*/
virtual string className() const { return "eoUniformSelect"; };
private:
};
#endif eoUniformSelect_h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoUniformSelect.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 eoUniformSelect_h
#define eoUniformSelect_h
// WARNING: 2 classes in this one - eoUniformSelect and eoCopySelect
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h>
//-----------------------------------------------------------------------------
/** eoUniformSelect: a selection method that selects ONE individual randomly
-MS- 22/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoUniformSelect: public eoSelectOne<EOT>
{
public:
/// (Default) Constructor.
eoUniformSelect():eoSelectOne<EOT>() {}
/// not a big deal!!!
virtual const EOT& operator()(const eoPop<EOT>& pop) {
return pop[rng.random(pop.size())] ;
}
/// Methods inherited from eoObject
//@{
/** Return the class id.
* @return the class name as a string
*/
virtual string className() const { return "eoUniformSelect"; };
private:
};
#endif eoUniformSelect_h

View file

@ -1,220 +1,221 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoWrappedOps.h
Derived from the General genetic operator, which can be used to wrap any unary or binary
operator. File also contains the eoCombinedOp, needed by the eoSequentialGOpSelector
(c) Maarten Keijzer (mak@dhi.dk) 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 eoWrappedOps_h
#define eoWrappedOps_h
//-----------------------------------------------------------------------------
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include "eoRNG.h"
using namespace std;
/// Wraps monary operators
template <class EOT>
class eoWrappedMonOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedMonOp(const eoMonOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {};
///
virtual ~eoWrappedMonOp() {}
/// Instantiates the abstract method
void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
EOT result = _in.select();
op( result );
_out.insert(result);
}
///
virtual string className() const {return "eoWrappedMonOp";};
private :
const eoMonOp<EOT>& op;
};
/// Wraps binary operators
template <class EOT>
class eoWrappedBinOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedBinOp(const eoBinOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
///
virtual ~eoWrappedBinOp() {}
/// Instantiates the abstract method. EOT should have copy ctor.
void operator()(eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
EOT out1 = _in.select();
const EOT& out2 = _in.select();
op(out1, out2);
_out.insert(out1);
}
///
virtual string className() const {return "eoWrappedBinOp";};
private :
const eoBinOp<EOT>& op;
};
/// Wraps Quadratic operators
template <class EOT>
class eoWrappedQuadraticOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedQuadraticOp(const eoQuadraticOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
///
virtual ~eoWrappedQuadraticOp() {}
/// Instantiates the abstract method. EOT should have copy ctor.
void operator()(eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
EOT out1 = _in.select();
EOT out2 = _in.select();
op(out1, out2);
_out.insert(out1);
_out.insert(out2);
}
///
virtual string className() const {return "eoWrappedQuadraticOp";};
private :
const eoQuadraticOp<EOT>& op;
};
/// Combines several ops
template <class EOT>
class eoCombinedOp : public eoGeneralOp<EOT>
{
public :
///
eoCombinedOp() : eoGeneralOp<EOT>() {}
///
virtual ~eoCombinedOp() {}
/// Adds a new operator to the combined Op
void addOp(eoGeneralOp<EOT>* _op)
{
ops.push_back(_op);
}
/// Erases all operators added so far
void clear(void) {
ops.resize(0);
}
/// Helper class to make sure that stuff that is inserted will be used again with the next operator
class eoIndiSelectorInserter : public eoIndiSelector<EOT>, public eoInserter<EOT>
{
public :
eoIndiSelectorInserter(eoIndiSelector<EOT>& _in)
: eoIndiSelector<EOT>(), eoInserter<EOT>(), in(_in)
{}
size_t size() const { return in.size(); }
const EOT& operator[](size_t _n) const { return in[_n]; }
const EOT& select(void)
{
if (results.empty())
{
return in.select();
}
// else we use the previously inserted individual,
// an iterator to it is stored in 'results', but the memory
// is kept by 'intermediate'.
list<EOT>::iterator it = *results.begin();
results.pop_front();
return *it;
}
void insert(const EOT& _eot)
{
intermediate.push_front(_eot);
results.push_front(intermediate.begin());
}
void fill(eoInserter<EOT>& _out)
{
typedef list<list<EOT>::iterator>::iterator Iterator;
for (Iterator it = results.begin(); it != results.end(); ++it)
{
_out.insert(**it);
}
results.clear();
intermediate.clear(); // reclaim memory
}
private :
eoIndiSelector<EOT>& in;
// using lists as we need to push and pop a lot
// 'results' are iterators to the contents of 'intermediate'
// to prevent copying to and from intermediate...
list<list<EOT>::iterator> results;
list<EOT> intermediate;
};
/// Applies all ops in the combined op
void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out ) const {
eoIndiSelectorInserter in_out(_in);
for (size_t i = 0; i < ops.size(); ++i)
{
(*ops[i])(in_out, in_out);
}
in_out.fill(_out);
}
private :
vector<eoGeneralOp<EOT>* > ops;
};
#endif eoGeneral_h
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
eoWrappedOps.h
Derived from the General genetic operator, which can be used to wrap any unary or binary
operator. File also contains the eoCombinedOp, needed by the eoSequentialGOpSelector
(c) Maarten Keijzer (mak@dhi.dk) 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 eoWrappedOps_h
#define eoWrappedOps_h
//-----------------------------------------------------------------------------
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include "eoRNG.h"
using namespace std;
/// Wraps monary operators
template <class EOT>
class eoWrappedMonOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedMonOp(const eoMonOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {};
///
virtual ~eoWrappedMonOp() {}
/// Instantiates the abstract method
void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
EOT result = _in.select();
op( result );
_out.insert(result);
}
///
virtual string className() const {return "eoWrappedMonOp";};
private :
const eoMonOp<EOT>& op;
};
/// Wraps binary operators
template <class EOT>
class eoWrappedBinOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedBinOp(const eoBinOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
///
virtual ~eoWrappedBinOp() {}
/// Instantiates the abstract method. EOT should have copy ctor.
void operator()(eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
EOT out1 = _in.select();
const EOT& out2 = _in.select();
op(out1, out2);
_out.insert(out1);
}
///
virtual string className() const {return "eoWrappedBinOp";};
private :
const eoBinOp<EOT>& op;
};
/// Wraps Quadratic operators
template <class EOT>
class eoWrappedQuadraticOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedQuadraticOp(const eoQuadraticOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
///
virtual ~eoWrappedQuadraticOp() {}
/// Instantiates the abstract method. EOT should have copy ctor.
void operator()(eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
EOT out1 = _in.select();
EOT out2 = _in.select();
op(out1, out2);
_out.insert(out1);
_out.insert(out2);
}
///
virtual string className() const {return "eoWrappedQuadraticOp";};
private :
const eoQuadraticOp<EOT>& op;
};
/// Combines several ops
template <class EOT>
class eoCombinedOp : public eoGeneralOp<EOT>
{
public :
///
eoCombinedOp() : eoGeneralOp<EOT>() {}
///
virtual ~eoCombinedOp() {}
/// Adds a new operator to the combined Op
void addOp(eoGeneralOp<EOT>* _op)
{
ops.push_back(_op);
}
/// Erases all operators added so far
void clear(void) {
ops.resize(0);
}
/// Helper class to make sure that stuff that is inserted will be used again with the next operator
class eoIndiSelectorInserter : public eoIndiSelector<EOT>, public eoInserter<EOT>
{
public :
eoIndiSelectorInserter(eoIndiSelector<EOT>& _in)
: eoIndiSelector<EOT>(), eoInserter<EOT>(), in(_in)
{}
size_t size() const { return in.size(); }
const EOT& operator[](size_t _n) const { return in[_n]; }
const EOT& select(void)
{
if (results.empty())
{
return in.select();
}
// else we use the previously inserted individual,
// an iterator to it is stored in 'results', but the memory
// is kept by 'intermediate'.
list<EOT>::iterator it = *results.begin();
results.pop_front();
return *it;
}
void insert(const EOT& _eot)
{
intermediate.push_front(_eot);
results.push_front(intermediate.begin());
}
void fill(eoInserter<EOT>& _out)
{
typedef list<list<EOT>::iterator>::iterator Iterator;
for (Iterator it = results.begin(); it != results.end(); ++it)
{
_out.insert(**it);
}
results.clear();
intermediate.clear(); // reclaim memory
}
private :
eoIndiSelector<EOT>& in;
// using lists as we need to push and pop a lot
// 'results' are iterators to the contents of 'intermediate'
// to prevent copying to and from intermediate...
list<list<EOT>::iterator> results;
list<EOT> intermediate;
};
/// Applies all ops in the combined op
void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out ) const {
eoIndiSelectorInserter in_out(_in);
for (size_t i = 0; i < ops.size(); ++i)
{
(*ops[i])(in_out, in_out);
}
in_out.fill(_out);
}
private :
vector<eoGeneralOp<EOT>* > ops;
};
#endif eoGeneral_h

View file

@ -1,106 +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 <eoUniform.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;
eoUniform<unsigned> uniform( 0, len );
unsigned pos1 = uniform(), pos2 = uniform() ;
applyAt( _eo1, _eo2, pos1, pos2 );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoXOver2";};
//@}
private:
#ifdef _MSC_VER
typedef EOT::Type Type;
#else
typedef typename EOT::Type Type;
#endif
/// applies operator to one gene in the EO
virtual void applyAt( EOT& _eo, EOT& _eo2,
unsigned _i, unsigned _j = 0) const {
if ( _j < _i )
swap( _i, _j );
unsigned len1 = _eo.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1;
if ( (_j > len) || (_i> len ) )
throw runtime_error( "xOver2: applying xOver past boundaries");
for ( unsigned i = _i; i < _j; i++ ) {
Type tmp = _eo.gene( i );
_eo.gene( i ) = _eo2.gene( i );
_eo2.gene( i ) = tmp ;
}
}
};
#endif
// -*- 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 <eoUniform.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;
eoUniform<unsigned> uniform( 0, len );
unsigned pos1 = uniform(), pos2 = uniform() ;
applyAt( _eo1, _eo2, pos1, pos2 );
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoXOver2";};
//@}
private:
#ifdef _MSC_VER
typedef EOT::Type Type;
#else
typedef typename EOT::Type Type;
#endif
/// applies operator to one gene in the EO
virtual void applyAt( EOT& _eo, EOT& _eo2,
unsigned _i, unsigned _j = 0) const {
if ( _j < _i )
swap( _i, _j );
unsigned len1 = _eo.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1;
if ( (_j > len) || (_i> len ) )
throw runtime_error( "xOver2: applying xOver past boundaries");
for ( unsigned i = _i; i < _j; i++ ) {
Type tmp = _eo.gene( i );
_eo.gene( i ) = _eo2.gene( i );
_eo2.gene( i ) = tmp ;
}
}
};
#endif

View file

@ -1,85 +1,85 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
rnd_generators.h
Some utility functors for generating random generators:
uniform_generator : generates uniform floats or doubles
random_generator : generates unsigneds, ints etc.
normal_generator : normally distributed floats or doubles
(c) Maarten Keijzer (mak@dhi.dk) 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 eoRND_GENERATORS_H
#define eoRND_GENERATORS_H
#include "eoRNG.h"
/**
The class uniform_generator can be used in the STL generate function
to easily generate random floats and doubles between [0, _max). _max
defaults to 1.0
*/
template <class T = double> class uniform_generator
{
public :
uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {}
virtual T operator()(void) { return (T) uniform.uniform(maxim); }
private :
T maxim;
eoRng& uniform;
};
/**
The class random_generator can be used in the STL generate function
to easily generate random ints between [0, _max).
*/
template <class T = uint32> class random_generator
{
public :
random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {}
virtual T operator()(void) { return (T) random.random(max); }
private :
T maxim;
eoRng& random;
};
/**
The class normal_generator can be used in the STL generate function
to easily generate gaussian distributed floats and doubles. The user
can supply a standard deviation which defaults to 1.
*/
template <class T = double> class normal_generator
{
public :
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
virtual T operator()(void) { return (T) normal.normal(stdev); }
private :
T stdev;
eoRng& normal;
};
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
rnd_generators.h
Some utility functors for generating random generators:
uniform_generator : generates uniform floats or doubles
random_generator : generates unsigneds, ints etc.
normal_generator : normally distributed floats or doubles
(c) Maarten Keijzer (mak@dhi.dk) 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 eoRND_GENERATORS_H
#define eoRND_GENERATORS_H
#include "eoRNG.h"
/**
The class uniform_generator can be used in the STL generate function
to easily generate random floats and doubles between [0, _max). _max
defaults to 1.0
*/
template <class T = double> class uniform_generator
{
public :
uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {}
virtual T operator()(void) { return (T) uniform.uniform(maxim); }
private :
T maxim;
eoRng& uniform;
};
/**
The class random_generator can be used in the STL generate function
to easily generate random ints between [0, _max).
*/
template <class T = uint32> class random_generator
{
public :
random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {}
virtual T operator()(void) { return (T) random.random(max); }
private :
T maxim;
eoRng& random;
};
/**
The class normal_generator can be used in the STL generate function
to easily generate gaussian distributed floats and doubles. The user
can supply a standard deviation which defaults to 1.
*/
template <class T = double> class normal_generator
{
public :
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
virtual T operator()(void) { return (T) normal.normal(stdev); }
private :
T stdev;
eoRng& normal;
};
#endif

View file

@ -1,313 +1,313 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
selectors.h
A bunch of useful selector functions. They generally have three forms:
template <class It>
It select(It begin, It end, params, eoRng& gen = rng);
template <class EOT>
const EOT& select(const eoPop<EOT>& pop, params, eoRng& gen = rng);
template <class EOT>
EOT& select(eoPop<EOT>& pop, params, eoRng& gen = rng);
where select is one of: roulette_wheel, deterministic_tournament
and stochastic_tournament (at the moment).
(c) Maarten Keijzer (mak@dhi.dk) 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 SELECT__H
#define SELECT__H
#include "eoRNG.h"
#include "eoException.h"
template <class EOT>
bool minimizing_fitness()
{
EOT eo1; // Assuming people don't do anything fancy in the default constructor!
EOT eo2;
/* Dear user, when the two line below do not compile you are most
likely not working with scalar fitness values. In that case we're sorry
but you cannot use lottery or roulette_wheel selection...
*/
eo1.fitness(0.0); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this
eo2.fitness(1.0);
return eo2 < eo1; // check whether we have a minimizing fitness
};
inline double scale_fitness(const std::pair<double, double>& _minmax, double _value)
{
if (_minmax.first == _minmax.second)
{
return 0.0; // no differences in fitness, population converged!
}
// else
return (_value - _minmax.first) / (_minmax.second - _minmax.first);
}
template <class It>
double sum_fitness(It begin, It end)
{
double sum = 0.0;
for (; begin != end; ++begin)
{
double v = static_cast<double>(begin->fitness());
if (v < 0.0)
throw eoNegativeFitnessException();
sum += v;
}
return sum;
}
template <class EOT>
double sum_fitness(const eoPop<EOT>& _pop)
{
return sum_fitness(_pop.begin(), _pop.end());
}
template <class EOT>
double sum_fitness(const eoPop<EOT>& _pop, std::pair<double, double>& _minmax)
{
eoPop<EOT>::const_iterator it = _pop.begin();
_minmax.first = it->fitness();
_minmax.second = it++->fitness();
for(; it != _pop.end(); ++it)
{
double v = static_cast<double>(it->fitness());
_minmax.first = std::min(_minmax.first, v);
_minmax.second = std::max(_minmax.second, v);
rawTotal += v;
}
if (minimizing_fitness<EOT>())
{
std::swap(_minmax.first, _minmax.second);
}
scaledTotal = 0.0;
// unfortunately a second loop is neccessary to scale the fitness
for (it = _pop.begin(); it != _pop.end(); ++it)
{
double v = scale_fitness(static_cast<double>(it->fitness()));
scaledTotal += v;
}
}
template <class It>
It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng)
{
float roulette = _gen.uniform(total);
It i = _begin;
while (roulette > 0.0)
{
roulette -= static_cast<double>(*(i++));
}
return --i;
}
template <class EOT>
const EOT& roulette_wheel(const eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
{
float roulette = _gen.uniform(total);
eoPop<EOT>::const_iterator i = _pop.begin();
while (roulette > 0.0)
{
roulette -= static_cast<double>((i++)->fitness());
}
return *--i;
}
template <class EOT>
EOT& roulette_wheel(eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
{
float roulette = _gen.uniform(total);
eoPop<EOT>::iterator i = _pop.begin();
while (roulette > 0.0)
{
roulette -= static_cast<double>((i++)->fitness());
}
return *--i;
}
template <class It>
It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
{
It best = _begin + _gen.random(_end - _begin);
for (unsigned i = 0; i < _t_size - 1; ++i)
{
It competitor = _begin + _gen.random(_end - _begin);
if (*best < *competitor)
{
best = competitor;
}
}
return best;
}
template <class EOT>
const EOT& deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
}
template <class EOT>
EOT& deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
}
template <class It>
It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
{
It worst = _begin + _gen.random(_end - _begin);
for (unsigned i = 0; i < _t_size - 1; ++i)
{
It competitor = _begin + _gen.random(_end - _begin);
if (competitor == worst)
{
--i;
continue; // try again
}
if (*competitor < *worst)
{
worst = competitor;
}
}
return worst;
}
template <class EOT>
const EOT& inverse_deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{
return *inverse_deterministic_tournament<EOT>(_pop.begin(), _pop.end(), _t_size, _gen);
}
template <class EOT>
EOT& inverse_deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{
return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
}
template <class It>
It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
{
It i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin);
bool return_better = _gen.flip(_t_rate);
if (*i1 < *i2)
{
if (return_better) return i2;
// else
return i1;
}
else
{
if (return_better) return i1;
// else
}
// else
return i2;
}
template <class EOT>
const EOT& stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
}
template <class EOT>
EOT& stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
}
template <class It>
It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
{
It i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin);
bool return_worse = _gen.flip(_t_rate);
if (*i1 < *i2)
{
if (return_worse) return i1;
// else
return i2;
}
else
{
if (return_worse) return i2;
// else
}
// else
return i1;
}
template <class EOT>
const EOT& inverse_stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
}
template <class EOT>
EOT& inverse_stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
}
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
selectors.h
A bunch of useful selector functions. They generally have three forms:
template <class It>
It select(It begin, It end, params, eoRng& gen = rng);
template <class EOT>
const EOT& select(const eoPop<EOT>& pop, params, eoRng& gen = rng);
template <class EOT>
EOT& select(eoPop<EOT>& pop, params, eoRng& gen = rng);
where select is one of: roulette_wheel, deterministic_tournament
and stochastic_tournament (at the moment).
(c) Maarten Keijzer (mak@dhi.dk) 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 SELECT__H
#define SELECT__H
#include "eoRNG.h"
#include "eoException.h"
template <class EOT>
bool minimizing_fitness()
{
EOT eo1; // Assuming people don't do anything fancy in the default constructor!
EOT eo2;
/* Dear user, when the two line below do not compile you are most
likely not working with scalar fitness values. In that case we're sorry
but you cannot use lottery or roulette_wheel selection...
*/
eo1.fitness(0.0); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this
eo2.fitness(1.0);
return eo2 < eo1; // check whether we have a minimizing fitness
};
inline double scale_fitness(const std::pair<double, double>& _minmax, double _value)
{
if (_minmax.first == _minmax.second)
{
return 0.0; // no differences in fitness, population converged!
}
// else
return (_value - _minmax.first) / (_minmax.second - _minmax.first);
}
template <class It>
double sum_fitness(It begin, It end)
{
double sum = 0.0;
for (; begin != end; ++begin)
{
double v = static_cast<double>(begin->fitness());
if (v < 0.0)
throw eoNegativeFitnessException();
sum += v;
}
return sum;
}
template <class EOT>
double sum_fitness(const eoPop<EOT>& _pop)
{
return sum_fitness(_pop.begin(), _pop.end());
}
template <class EOT>
double sum_fitness(const eoPop<EOT>& _pop, std::pair<double, double>& _minmax)
{
eoPop<EOT>::const_iterator it = _pop.begin();
_minmax.first = it->fitness();
_minmax.second = it++->fitness();
for(; it != _pop.end(); ++it)
{
double v = static_cast<double>(it->fitness());
_minmax.first = std::min(_minmax.first, v);
_minmax.second = std::max(_minmax.second, v);
rawTotal += v;
}
if (minimizing_fitness<EOT>())
{
std::swap(_minmax.first, _minmax.second);
}
scaledTotal = 0.0;
// unfortunately a second loop is neccessary to scale the fitness
for (it = _pop.begin(); it != _pop.end(); ++it)
{
double v = scale_fitness(static_cast<double>(it->fitness()));
scaledTotal += v;
}
}
template <class It>
It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng)
{
float roulette = _gen.uniform(total);
It i = _begin;
while (roulette > 0.0)
{
roulette -= static_cast<double>(*(i++));
}
return --i;
}
template <class EOT>
const EOT& roulette_wheel(const eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
{
float roulette = _gen.uniform(total);
eoPop<EOT>::const_iterator i = _pop.begin();
while (roulette > 0.0)
{
roulette -= static_cast<double>((i++)->fitness());
}
return *--i;
}
template <class EOT>
EOT& roulette_wheel(eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
{
float roulette = _gen.uniform(total);
eoPop<EOT>::iterator i = _pop.begin();
while (roulette > 0.0)
{
roulette -= static_cast<double>((i++)->fitness());
}
return *--i;
}
template <class It>
It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
{
It best = _begin + _gen.random(_end - _begin);
for (unsigned i = 0; i < _t_size - 1; ++i)
{
It competitor = _begin + _gen.random(_end - _begin);
if (*best < *competitor)
{
best = competitor;
}
}
return best;
}
template <class EOT>
const EOT& deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
}
template <class EOT>
EOT& deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
}
template <class It>
It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
{
It worst = _begin + _gen.random(_end - _begin);
for (unsigned i = 0; i < _t_size - 1; ++i)
{
It competitor = _begin + _gen.random(_end - _begin);
if (competitor == worst)
{
--i;
continue; // try again
}
if (*competitor < *worst)
{
worst = competitor;
}
}
return worst;
}
template <class EOT>
const EOT& inverse_deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{
return *inverse_deterministic_tournament<EOT>(_pop.begin(), _pop.end(), _t_size, _gen);
}
template <class EOT>
EOT& inverse_deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{
return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
}
template <class It>
It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
{
It i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin);
bool return_better = _gen.flip(_t_rate);
if (*i1 < *i2)
{
if (return_better) return i2;
// else
return i1;
}
else
{
if (return_better) return i1;
// else
}
// else
return i2;
}
template <class EOT>
const EOT& stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
}
template <class EOT>
EOT& stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
}
template <class It>
It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
{
It i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin);
bool return_worse = _gen.flip(_t_rate);
if (*i1 < *i2)
{
if (return_worse) return i1;
// else
return i2;
}
else
{
if (return_worse) return i2;
// else
}
// else
return i1;
}
template <class EOT>
const EOT& inverse_stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
}
template <class EOT>
EOT& inverse_stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
}
#endif