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

View file

@ -1,228 +1,228 @@
#ifndef node_pool_h #ifndef node_pool_h
#define node_pool_h #define node_pool_h
class MemPool class MemPool
{ {
public : public :
MemPool(unsigned int sz) : esize(sz<sizeof(Link)? sizeof(Link) : sz) {} MemPool(unsigned int sz) : esize(sz<sizeof(Link)? sizeof(Link) : sz) {}
~MemPool() ~MemPool()
{ {
Chunk* n = chunks; Chunk* n = chunks;
while(n) while(n)
{ {
Chunk* p = n; Chunk* p = n;
n = n->next; n = n->next;
delete p; delete p;
} }
} }
void* allocate() void* allocate()
{ {
if (head == 0) grow(); if (head == 0) grow();
Link* p = head; Link* p = head;
head = p->next; head = p->next;
return static_cast<void*>(p); return static_cast<void*>(p);
} }
void deallocate(void* b) void deallocate(void* b)
{ {
Link* p = static_cast<Link*>(b); Link* p = static_cast<Link*>(b);
p->next = head; p->next = head;
head = p; head = p;
} }
private : private :
void grow() void grow()
{ {
Chunk* n = new Chunk; Chunk* n = new Chunk;
n->next = chunks; n->next = chunks;
chunks = n; chunks = n;
const int nelem = Chunk::size/esize; const int nelem = Chunk::size/esize;
char* start = n->mem; char* start = n->mem;
char* last = &start[(nelem-1)*esize]; char* last = &start[(nelem-1)*esize];
for (char* p = start; p < last; p += esize) for (char* p = start; p < last; p += esize)
{ {
reinterpret_cast<Link*>(p)->next = reinterpret_cast<Link*>(p)->next =
reinterpret_cast<Link*>(p + esize); reinterpret_cast<Link*>(p + esize);
} }
reinterpret_cast<Link*>(last)->next = 0; reinterpret_cast<Link*>(last)->next = 0;
head = reinterpret_cast<Link*>(start); head = reinterpret_cast<Link*>(start);
} }
struct Link struct Link
{ {
Link* next; Link* next;
}; };
struct Chunk struct Chunk
{ {
enum {size = 8 * 1024 - 16}; enum {size = 8 * 1024 - 16};
Chunk* next; Chunk* next;
char mem[size]; char mem[size];
}; };
Chunk* chunks; Chunk* chunks;
const unsigned int esize; const unsigned int esize;
Link* head; Link* head;
}; };
template<class T> template<class T>
class Node_alloc class Node_alloc
{ {
public : public :
Node_alloc() {}; Node_alloc() {};
T* allocate(void) T* allocate(void)
{ {
T* t = static_cast<T*>(mem.allocate()); T* t = static_cast<T*>(mem.allocate());
t = new (t) T; t = new (t) T;
//t->T(); // call constructor; //t->T(); // call constructor;
return t; return t;
} }
void deallocate(T* t) void deallocate(T* t)
{ {
t->~T(); // call destructor t->~T(); // call destructor
mem.deallocate(static_cast<void*>(t)); mem.deallocate(static_cast<void*>(t));
} }
private : private :
static MemPool mem; static MemPool mem;
}; };
template <class T> template <class T>
class Standard_alloc class Standard_alloc
{ {
public : public :
Standard_alloc() {} Standard_alloc() {}
T* allocate(size_t arity = 1) T* allocate(size_t arity = 1)
{ {
if (arity == 0) if (arity == 0)
return 0; return 0;
return new T [arity]; return new T [arity];
} }
void deallocate(T* t, size_t arity = 1) void deallocate(T* t, size_t arity = 1)
{ {
if (arity == 0) if (arity == 0)
return ; return ;
delete [] t; delete [] t;
} }
}; };
template <class T> template <class T>
class Standard_Node_alloc class Standard_Node_alloc
{ {
public : public :
Standard_Node_alloc() {} Standard_Node_alloc() {}
T* allocate(void) T* allocate(void)
{ {
return new T;// [arity]; return new T;// [arity];
} }
void deallocate(T* t) void deallocate(T* t)
{ {
delete t; delete t;
} }
}; };
template <class T> template <class T>
class Tree_alloc class Tree_alloc
{ {
public : public :
Tree_alloc() {} Tree_alloc() {}
T* allocate(size_t arity) T* allocate(size_t arity)
{ {
T* t; T* t;
switch(arity) switch(arity)
{ {
case 0 : return 0; case 0 : return 0;
case 1 : case 1 :
{ {
t = static_cast<T*>(mem1.allocate()); t = static_cast<T*>(mem1.allocate());
new (t) T; new (t) T;
break; break;
} }
case 2 : case 2 :
{ {
t = static_cast<T*>(mem2.allocate()); t = static_cast<T*>(mem2.allocate());
new (t) T; new (t) T;
new (&t[1]) T; new (&t[1]) T;
break; break;
} }
case 3 : case 3 :
{ {
t = static_cast<T*>(mem3.allocate()); t = static_cast<T*>(mem3.allocate());
new (t) T; new (t) T;
new (&t[1]) T; new (&t[1]) T;
new (&t[2]) T; new (&t[2]) T;
break; break;
} }
default : default :
{ {
return new T[arity]; return new T[arity];
} }
} }
return t; return t;
} }
void deallocate(T* t, size_t arity) void deallocate(T* t, size_t arity)
{ {
switch(arity) switch(arity)
{ {
case 0: return; case 0: return;
case 3 : case 3 :
{ {
t[2].~T(); t[1].~T(); t[0].~T(); t[2].~T(); t[1].~T(); t[0].~T();
mem3.deallocate(static_cast<void*>(t)); mem3.deallocate(static_cast<void*>(t));
return; return;
} }
case 2 : case 2 :
{ {
t[1].~T(); t[0].~T(); t[1].~T(); t[0].~T();
mem2.deallocate(static_cast<void*>(t)); mem2.deallocate(static_cast<void*>(t));
return; return;
} }
case 1 : case 1 :
{ {
t[0].~T(); t[0].~T();
mem1.deallocate(static_cast<void*>(t)); mem1.deallocate(static_cast<void*>(t));
return; return;
} }
default : default :
{ {
delete [] t; delete [] t;
return; return;
} }
} }
} }
private : private :
static MemPool mem1; static MemPool mem1;
static MemPool mem2; static MemPool mem2;
static MemPool mem3; static MemPool mem3;
}; };
// static (non thread_safe) memory pools // static (non thread_safe) memory pools
template <class T> MemPool Node_alloc<T>::mem = sizeof(T); 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>::mem1 = sizeof(T);
template <class T> MemPool Tree_alloc<T>::mem2 = sizeof(T) * 2; template <class T> MemPool Tree_alloc<T>::mem2 = sizeof(T) * 2;
template <class T> MemPool Tree_alloc<T>::mem3 = sizeof(T) * 3; template <class T> MemPool Tree_alloc<T>::mem3 = sizeof(T) * 3;
#endif #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; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
compatibility.h compatibility.h
File to store some compiler specific stuff in. Currently handles, or File to store some compiler specific stuff in. Currently handles, or
least tries to handle the min() max() problems when using MSVC least tries to handle the min() max() problems when using MSVC
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef COMPAT_H #ifndef COMPAT_H
#define COMPAT_H #define COMPAT_H
#include <string> #include <string>
#include <iostream> #include <iostream>
#ifdef _1__GNUC__ #ifdef _1__GNUC__
// Specifics for GNUC // Specifics for GNUC
#define NO_GOOD_ISTREAM_ITERATORS #define NO_GOOD_ISTREAM_ITERATORS
#endif #endif
#ifdef _MSC_VER #ifdef _MSC_VER
/* /*
Maarten: added this code here because Mirkosoft has the Maarten: added this code here because Mirkosoft has the
nasty habit of #define min and max in stdlib.h (and windows.h) 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) I'm trying to undo this horrible macro magic (microsoft yet macrohard)
here. Sure hope it works here. Sure hope it works
*/ */
#include <stdlib.h> #include <stdlib.h>
#ifdef min #ifdef min
#undef min #undef min
#undef max // as they come in pairs #undef max // as they come in pairs
#endif #endif
// add min and max to std... // add min and max to std...
namespace std namespace std
{ {
template <class T> T min(const T& a, const T& b) template <class T> T min(const T& a, const T& b)
{ {
if(a < b) if(a < b)
return a; return a;
// else // else
return b; return b;
} }
template <class T> T max(const T& a, const T& b) template <class T> T max(const T& a, const T& b)
{ {
if(a > b) if(a > b)
return a; return a;
// else // else
return b; return b;
} }
} }
#endif // _MSC_VER #endif // _MSC_VER
#endif #endif

View file

@ -1,108 +1,109 @@
// eoAged.h // eoAged.h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoAge.h // eoAge.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef EOAGED_H #ifndef EOAGED_H
#define EOAGED_H #define EOAGED_H
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <iostream> // istream, ostream #include <iostream> // istream, ostream
#include <string> // para string #include <string> // para string
using namespace std; using namespace std;
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoAge // eoAge
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** eoAge is a template class that adds an age to an object.\\ /** 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 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, and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className,
printOn, readFrom. printOn, readFrom.
@see eoObject @see eoObject
*/ */
template <class Object> template <class Object>
class eoAged: public Object class eoAged: public Object
{ {
public: public:
/// Main ctor from an already built Object. /// Main ctor from an already built Object.
eoAged( const Object& _o): Object( _o ), age(0) {}; eoAged( const Object& _o): Object( _o ), age(0) {};
/// Copy constructor. /// Copy constructor.
eoAged( const eoAged& _a): Object( _a ), age( _a.age ) {}; eoAged( const eoAged& _a): Object( _a ), age( _a.age ) {};
/// Virtual dtor. They are needed in virtual class hierarchies /// Virtual dtor. They are needed in virtual class hierarchies
virtual ~eoAged() {}; virtual ~eoAged() {};
///returns the age of the object ///returns the age of the object
unsigned long Age() const {return age;} unsigned long Age() const {return age;}
/// Increments age /// Increments age
const eoAged& operator ++ () { age++; return *this;} const eoAged& operator ++ () { age++; return *this;}
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d readFrom and printOn are directly inherited from eo1d
*/ */
//@{ //@{
/** Return the class id. This should be redefined in each class; but /** Return the class id. This should be redefined in each class; but
it's got code as an example of implementation. Only "leaf" classes it's got code as an example of implementation. Only "leaf" classes
can be non-virtual. can be non-virtual.
*/ */
virtual string className() const { return string("eoAged")+Object::className(); }; virtual string className() const { return string("eoAged")+Object::className(); };
/** /**
* Read object. * Read object.
* @param _is A istream. * @param _is A istream.
* @throw runtime_exception If a valid object can't be read. * @throw runtime_exception If a valid object can't be read.
*/ */
virtual void readFrom(istream& _is) { virtual void readFrom(istream& _is) {
Object::readFrom( _is ); Object::readFrom( _is );
_is >> age; _is >> age;
} }
/** /**
* Write object. It's called printOn since it prints the object _on_ a stream. * Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream. * @param _os A ostream.
*/ */
virtual void printOn(ostream& _os) const{ virtual void printOn(ostream& _os) const{
Object::printOn( _os ); Object::printOn( _os );
_os << age; _os << age;
} }
//@} //@}
private: private:
/** Default Constructor. \\ /** Default Constructor. \\
It´s private so that it is not used anywhere; the right way of using this object 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 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*/ it´s turned into an Aged object*/
eoAged(): Object(), age(0) {}; eoAged(): Object(), age(0) {};
unsigned long age; unsigned long age;
}; };
#endif EOAGE_H #endif EOAGE_H

View file

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

View file

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

View file

@ -1,61 +1,62 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoAtomMutator.h // eoAtomMutator.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOATOMMUTATOR_H #ifndef _EOATOMMUTATOR_H
#define _EOATOMMUTATOR_H #define _EOATOMMUTATOR_H
/** Abstract base class for functors that modify a single element in an EO /** 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 that is composed of several atomic components. An atom would, for instance, flip
a bit, or change a real number, or things like that. a bit, or change a real number, or things like that.
*/ */
template <class T> template <class T>
class eoAtomMutator: public eoPrintable { class eoAtomMutator: public eoPrintable {
public: public:
/// ///
eoAtomMutator() {}; eoAtomMutator() {};
/// ///
virtual ~eoAtomMutator() {}; virtual ~eoAtomMutator() {};
/// ///
virtual void operator()( T& _val ) const = 0; virtual void operator()( T& _val ) const = 0;
/** @name Methods from eoObject /** @name Methods from eoObject
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
/// ///
virtual string className() const {return "eoAtomMutator";}; virtual string className() const {return "eoAtomMutator";};
/// ///
void printOn(ostream& _os) const { _os << className() << endl; }; void printOn(ostream& _os) const { _os << className() << endl; };
//@} //@}
}; };
#endif #endif

View file

@ -1,54 +1,54 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoInserter.h eoInserter.h
Abstract population insertion operator, which is used by the eoGeneralOps Abstract population insertion operator, which is used by the eoGeneralOps
to insert the results in the (intermediate) population. This file also to insert the results in the (intermediate) population. This file also
contains the definitions of a derived classes that implements a back inserter, contains the definitions of a derived classes that implements a back inserter,
probably the only efficient inserter for populations of type vector. probably the only efficient inserter for populations of type vector.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoBackInserter_h #ifndef eoBackInserter_h
#define eoBackInserter_h #define eoBackInserter_h
#include "eoInserter.h" #include "eoInserter.h"
/** /**
* eoBackInserter: Interface class that enables an operator to insert * eoBackInserter: Interface class that enables an operator to insert
new individuals at the back of the new population. new individuals at the back of the new population.
*/ */
template <class EOT> template <class EOT>
class eoBackInserter : public eoPopInserter<EOT> class eoBackInserter : public eoPopInserter<EOT>
{ {
public : public :
eoBackInserter(void) : eoPopInserter<EOT>() {} eoBackInserter(void) : eoPopInserter<EOT>() {}
void insert(const EOT& _eot) void insert(const EOT& _eot)
{ {
pop().push_back(_eot); pop().push_back(_eot);
} }
string className(void) const { return "eoBackInserter"; } string className(void) const { return "eoBackInserter"; }
}; };
#endif #endif

View file

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

View file

@ -1,119 +1,120 @@
// eoBitOpFactory.h // eoBitOpFactory.h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoOpFactory.h // eoOpFactory.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOBITOPFACTORY_H #ifndef _EOBITOPFACTORY_H
#define _EOBITOPFACTORY_H #define _EOBITOPFACTORY_H
#include <eoOpFactory.h> #include <eoOpFactory.h>
#include <eoBitOp.h> #include <eoBitOp.h>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** EO Factory. An instance of the factory class to create operators that act /** EO Factory. An instance of the factory class to create operators that act
on bitstring chromosomes. Only those chromosomes can instantiate the operators on bitstring chromosomes. Only those chromosomes can instantiate the operators
that are created here that are created here
@see eoSelect*/ @see eoSelect*/
template< class EOT> template< class EOT>
class eoBitOpFactory: public eoOpFactory<EOT> { class eoBitOpFactory: public eoOpFactory<EOT> {
public: public:
/// @name ctors and dtors /// @name ctors and dtors
//{@ //{@
/// constructor /// constructor
eoBitOpFactory( ) {}; eoBitOpFactory( ) {};
/// destructor /// destructor
virtual ~eoBitOpFactory() {}; virtual ~eoBitOpFactory() {};
//@} //@}
/** Another factory method: creates an object from an istream, reading from /** 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\\ it whatever is needed to create the object. Usually, the format for the istream will be\\
objectType parameter1 parameter2 ... parametern\\ objectType parameter1 parameter2 ... parametern\\
If there are problems, an exception is raised; it should be caught at the If there are problems, an exception is raised; it should be caught at the
upper level, because it might be something for that level\\ upper level, because it might be something for that level\\
At the same time, it catches exceptions thrown at a lower level, which will 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 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 @param _is an stream from where a single line will be read
@throw runtime_exception if the object type is not known @throw runtime_exception if the object type is not known
*/ */
virtual eoOp<EOT>* make(istream& _is) { virtual eoOp<EOT>* make(istream& _is) {
eoOp<EOT> * opPtr = NULL; eoOp<EOT> * opPtr = NULL;
try { try {
opPtr = eoOpFactory<EOT>::make( _is ); opPtr = eoOpFactory<EOT>::make( _is );
} catch ( const string& objectTypeStr ) { } catch ( const string& objectTypeStr ) {
if ( objectTypeStr == "eoBinRandom") { if ( objectTypeStr == "eoBinRandom") {
opPtr = new eoBinRandom<EOT>(); opPtr = new eoBinRandom<EOT>();
} }
if ( objectTypeStr == "eoBinBitFlip" ) { if ( objectTypeStr == "eoBinBitFlip" ) {
opPtr = new eoBinBitFlip<EOT>( ); opPtr = new eoBinBitFlip<EOT>( );
} }
if ( objectTypeStr == "eoBinMutation" ) { if ( objectTypeStr == "eoBinMutation" ) {
float rate; float rate;
_is >> rate; _is >> rate;
opPtr = new eoBinMutation<EOT>( rate ); opPtr = new eoBinMutation<EOT>( rate );
} }
if ( objectTypeStr == "eoBinInversion" ) { if ( objectTypeStr == "eoBinInversion" ) {
opPtr = new eoBinInversion<EOT>( ); opPtr = new eoBinInversion<EOT>( );
} }
if ( objectTypeStr == "eoBinNext" ) { if ( objectTypeStr == "eoBinNext" ) {
opPtr = new eoBinNext<EOT>( ); opPtr = new eoBinNext<EOT>( );
} }
if ( objectTypeStr == "eoBinPrev" ) { if ( objectTypeStr == "eoBinPrev" ) {
opPtr = new eoBinPrev<EOT>( ); opPtr = new eoBinPrev<EOT>( );
} }
if ( objectTypeStr == "eoBinNext" ) { if ( objectTypeStr == "eoBinNext" ) {
opPtr = new eoBinNext<EOT>( ); opPtr = new eoBinNext<EOT>( );
} }
if ( objectTypeStr == "eoBinCrossover" ) { if ( objectTypeStr == "eoBinCrossover" ) {
opPtr = new eoBinCrossover<EOT>( ); opPtr = new eoBinCrossover<EOT>( );
} }
if ( objectTypeStr == "eoBinNxOver" ) { if ( objectTypeStr == "eoBinNxOver" ) {
unsigned nPoints; unsigned nPoints;
_is >> nPoints; _is >> nPoints;
opPtr = new eoBinNxOver<EOT>( nPoints ); opPtr = new eoBinNxOver<EOT>( nPoints );
} }
if ( objectTypeStr == "eoBinGxOver" ) { if ( objectTypeStr == "eoBinGxOver" ) {
unsigned geneSize, nPoints; unsigned geneSize, nPoints;
_is >> geneSize >> nPoints; _is >> geneSize >> nPoints;
opPtr = new eoBinGxOver<EOT>( geneSize, nPoints ); opPtr = new eoBinGxOver<EOT>( geneSize, nPoints );
} }
if ( objectTypeStr == "eoBinUxOver" ) { if ( objectTypeStr == "eoBinUxOver" ) {
float rate; float rate;
_is >> rate; _is >> rate;
opPtr = new eoBinUxOver<EOT>( rate ); opPtr = new eoBinUxOver<EOT>( rate );
} }
if ( !opPtr ) { // to be caught by the upper level if ( !opPtr ) { // to be caught by the upper level
throw objectTypeStr; throw objectTypeStr;
} }
} }
return opPtr; return opPtr;
}; };
}; };
#endif _EOBITOPFACTORY_H #endif _EOBITOPFACTORY_H

View file

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

View file

@ -1,65 +1,64 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoData.h eoData.h
Some numeric limits and types and things like that; with #ifdefs to keep Some numeric limits and types and things like that; with #ifdefs to keep
compatibility compatibility
(c) GeNeura Team & Maarten Keijzer, 1998, 1999, 2000 (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 This library is distributed in the hope that it will be useful,
modify it under the terms of the GNU Lesser General Public but WITHOUT ANY WARRANTY; without even the implied warranty of
License as published by the Free Software Foundation; either MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
version 2 of the License, or (at your option) any later version. Lesser General Public License for more details.
This library is distributed in the hope that it will be useful, You should have received a copy of the GNU Lesser General Public
but WITHOUT ANY WARRANTY; without even the implied warranty of License along with this library; if not, write to the Free Software
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Lesser General Public License for more details.
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
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 #ifndef EODATA_H
#define EODATA_H
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ //-----------------------------------------------------------------------------
#ifndef EODATA_H #include <vector> // vector
#define EODATA_H #include <set> // set
#include <string> // string
//-----------------------------------------------------------------------------
using namespace std;
#include <vector> // vector
#include <set> // set
#include <string> // string #ifdef _MSC_VER
#include <limits> // MAXDOUBLE
using namespace std; #define MAXFLOAT numeric_limits<float>::max()
#define MINFLOAT numeric_limits<float>::min()
#define MAXDOUBLE numeric_limits<double>::max()
#ifdef _MSC_VER #define MAXINT numeric_limits<int>::max()
#include <limits> // MAXDOUBLE #else
#define MAXFLOAT numeric_limits<float>::max() #include <float.h>
#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> #include <limits.h>
#ifndef _WIN32 // should be the define for UN*X flavours: _POSIX?? #ifndef _WIN32 // should be the define for UN*X flavours: _POSIX??
#include <values.h> #include <values.h>
#endif #endif
#ifndef MAXFLOAT #ifndef MAXFLOAT
#define MAXFLOAT (float)1e127 #define MAXFLOAT (float)1e127
#define MAXDOUBLE (double)1.79769313486231570e+308 #define MAXDOUBLE (double)1.79769313486231570e+308
#define MAXINT 2147483647 #define MAXINT 2147483647
#endif #endif
#endif #endif
#ifndef _MSC_VER #ifndef _MSC_VER
#include <math.h> #include <math.h>
#define _isnan isnan #define _isnan isnan
#endif #endif
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif EODATA_H #endif EODATA_H

View file

@ -1,70 +1,71 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoDetTournament.h // eoDetTournament.h
// (c) GeNeura Team, 1998 - EEAAX 1999 // (c) GeNeura Team, 1998 - EEAAX 1999
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoDetTournament_h #ifndef eoDetTournament_h
#define eoDetTournament_h #define eoDetTournament_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <functional> // #include <functional> //
#include <numeric> // accumulate #include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT #include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include "selectors.h" #include "selectors.h"
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** eoDetTournament: a selection method that selects ONE individual by /** eoDetTournament: a selection method that selects ONE individual by
deterministic tournament deterministic tournament
-MS- 24/10/99 */ -MS- 24/10/99 */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
template <class EOT> class eoDetTournament: public eoSelectOne<EOT> template <class EOT> class eoDetTournament: public eoSelectOne<EOT>
{ {
public: public:
/// (Default) Constructor. /// (Default) Constructor.
eoDetTournament(unsigned _Tsize = 2 ):eoSelectOne<EOT>(), Tsize(_Tsize) { eoDetTournament(unsigned _Tsize = 2 ):eoSelectOne<EOT>(), Tsize(_Tsize) {
// consistency check // consistency check
if (Tsize < 2) { if (Tsize < 2) {
cout << "Warning, Tournament size should be >= 2\nAdjusted\n"; cout << "Warning, Tournament size should be >= 2\nAdjusted\n";
Tsize = 2; Tsize = 2;
} }
} }
virtual const EOT& operator()(const eoPop<EOT>& pop) virtual const EOT& operator()(const eoPop<EOT>& pop)
{ {
return deterministic_tournament(pop, Tsize)(); return deterministic_tournament(pop, Tsize)();
} }
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
string className() const {return "eoDetTournament";}; string className() const {return "eoDetTournament";};
private: private:
unsigned Tsize; unsigned Tsize;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif eoDetTournament_h #endif eoDetTournament_h

View file

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

View file

@ -1,69 +1,69 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoDetTournamentInserter.h eoDetTournamentInserter.h
Concrete steady state inserter. It is initialized with a population and Concrete steady state inserter. It is initialized with a population and
inserts individuals in the population based on an inverse deterministic inserts individuals in the population based on an inverse deterministic
tournament tournament
(c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoDetTournamentInserter_h #ifndef eoDetTournamentInserter_h
#define eoDetTournamentInserter_h #define eoDetTournamentInserter_h
#include "eoSteadyStateInserter.h" #include "eoSteadyStateInserter.h"
#include "selectors.h" #include "selectors.h"
/** /**
* eoDetTournamentInserter: Uses an inverse deterministic tournament to figure * eoDetTournamentInserter: Uses an inverse deterministic tournament to figure
* out who gets overridden by the new individual. It resets the fitness of the * out who gets overridden by the new individual. It resets the fitness of the
* individual. * individual.
*/ */
template <class EOT> template <class EOT>
class eoDetTournamentInserter : public eoSteadyStateInserter<EOT> class eoDetTournamentInserter : public eoSteadyStateInserter<EOT>
{ {
public : public :
eoDetTournamentInserter(eoEvalFunc<EOT>& _eval, unsigned _t_size) : t_size(_t_size), eoSteadyStateInserter<EOT>(_eval) eoDetTournamentInserter(eoEvalFunc<EOT>& _eval, unsigned _t_size) : t_size(_t_size), eoSteadyStateInserter<EOT>(_eval)
{ {
if (t_size < 2) if (t_size < 2)
{ // warning, error? { // warning, error?
t_size = 2; t_size = 2;
} }
} }
void insert(const EOT& _eot) void insert(const EOT& _eot)
{ {
EOT& eo = inverse_deterministic_tournament<EOT>(pop(), t_size); EOT& eo = inverse_deterministic_tournament<EOT>(pop(), t_size);
eo = _eot; // overwrite loser of tournament eo = _eot; // overwrite loser of tournament
eo.invalidate(); // This line should probably be removed when all genetic operators do this themselves eo.invalidate(); // This line should probably be removed when all genetic operators do this themselves
eval(eo); // Evaluate after insert eval(eo); // Evaluate after insert
} }
string className(void) const { return "eoDetTournamentInserter"; } string className(void) const { return "eoDetTournamentInserter"; }
private : private :
unsigned t_size; unsigned t_size;
}; };
#endif #endif

View file

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

View file

@ -1,125 +1,126 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoESChrom.h // eoESChrom.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _eoESCHROM_H #ifndef _eoESCHROM_H
#define _eoESCHROM_H #define _eoESCHROM_H
// STL libraries // STL libraries
#include <vector> // For vector<> #include <vector> // For vector<>
#include <stdexcept> #include <stdexcept>
#include <strstream> #include <strstream>
#include <iostream> // for ostream #include <iostream> // for ostream
// EO includes // EO includes
#include <eoVector.h> #include <eoVector.h>
/**@name Chromosomes for evolution strategies /**@name Chromosomes for evolution strategies
Each chromosome in an evolution strategies is composed of a vector of floating point 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 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 /** Each gene in an Evolution Strategies is composed of a value plus an standard
deviation, sigma, used for mutation*/ deviation, sigma, used for mutation*/
struct eoESGene { struct eoESGene {
double val, sigma; double val, sigma;
eoESGene( double _val = 0, double _sigma = 0 ): val( _val ), sigma( _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 /// Tricky operator to avoid errors in some VC++ systems, namely VC 5.0 SP3
bool operator < ( eoESGene _e1, eoESGene _e2 ) { bool operator < ( eoESGene _e1, eoESGene _e2 ) {
return _e1.val < _e2.val; return _e1.val < _e2.val;
} }
/// Tricky operator to avoid errors in some VC++ systems /// Tricky operator to avoid errors in some VC++ systems
bool operator == ( eoESGene _e1, eoESGene _e2 ) { bool operator == ( eoESGene _e1, eoESGene _e2 ) {
return ( _e1.val == _e2.val ) && ( _e1.sigma == _e2.sigma ) ; return ( _e1.val == _e2.val ) && ( _e1.sigma == _e2.sigma ) ;
} }
/// ///
ostream & operator << ( ostream& _s, const eoESGene& _e ) { ostream & operator << ( ostream& _s, const eoESGene& _e ) {
_s << _e.val << ", " << _e.sigma << " | "; _s << _e.val << ", " << _e.sigma << " | ";
return _s; return _s;
} }
/// Dummy >> /// Dummy >>
istream & operator >> ( istream& _s, const eoESGene& _e ) { istream & operator >> ( istream& _s, const eoESGene& _e ) {
_s >> _e.val; _s >> _e.val;
_s >> _e.sigma; _s >> _e.sigma;
return _s; return _s;
} }
/** Basic chromosome for evolution strategies (ES), as defined by Rechenberg and /** 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 Schwefel. Each chromosomes is composed of "genes"; each one of then is an eoESGene
@see eoESGene @see eoESGene
*/ */
template <typename fitT = float > template <typename fitT = float >
class eoESChrom: public eoVector<eoESGene, fitT> { class eoESChrom: public eoVector<eoESGene, fitT> {
public: public:
/// Basic ctor /// Basic ctor
eoESChrom( ):eoVector<eoESGene, fitT>() {}; eoESChrom( ):eoVector<eoESGene, fitT>() {};
/** Ctor using a couple of random number generators /** Ctor using a couple of random number generators
@param _size Lineal length of the object @param _size Lineal length of the object
@param _rnd a random number generator, which returns a random value each time it´s called. @param _rnd a random number generator, which returns a random value each time it´s called.
@param _rndS another one, for the sigma @param _rndS another one, for the sigma
*/ */
eoESChrom( unsigned _size, eoRnd<double>& _rnd, eoRnd<double>& _rndS ) eoESChrom( unsigned _size, eoRnd<double>& _rnd, eoRnd<double>& _rndS )
: eoVector<eoESGene, fitT>( _size ){ : eoVector<eoESGene, fitT>( _size ){
for ( iterator i = begin(); i != end(); i ++ ) { for ( iterator i = begin(); i != end(); i ++ ) {
i->val = _rnd(); i->val = _rnd();
i->sigma = _rndS(); i->sigma = _rndS();
} }
}; };
/// Copy ctor /// Copy ctor
eoESChrom( const eoESChrom& _eoes): eoVector<eoESGene, fitT>( _eoes ) {}; eoESChrom( const eoESChrom& _eoes): eoVector<eoESGene, fitT>( _eoes ) {};
/// Assignment operator /// Assignment operator
const eoESChrom& operator =( const eoESChrom & _eoes ) { const eoESChrom& operator =( const eoESChrom & _eoes ) {
if ( this != &_eoes ){ if ( this != &_eoes ){
eoVector<eoESGene, fitT>::operator=( _eoes ); eoVector<eoESGene, fitT>::operator=( _eoes );
} }
return *this; return *this;
} }
/// ///
~eoESChrom() {}; ~eoESChrom() {};
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d readFrom and printOn are directly inherited from eo1d
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
string className() const {return "eoESChrom";}; string className() const {return "eoESChrom";};
//@} //@}
}; };
//@} //@}
#endif #endif

View file

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

View file

@ -1,84 +1,85 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoEasyEA.h // eoEasyEA.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _eoEasyEA_h #ifndef _eoEasyEA_h
#define _eoEasyEA_h #define _eoEasyEA_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <eoGeneration.h> // eoPop #include <eoGeneration.h> // eoPop
#include <eoTerm.h> #include <eoTerm.h>
/** EOEasyEA: /** EOEasyEA:
An easy-to-use evolutionary algorithm; you can use any chromosome, An easy-to-use evolutionary algorithm; you can use any chromosome,
and any selection transformation, merging and evaluation and any selection transformation, merging and evaluation
algorithms; you can even change in runtime parameters of those algorithms; you can even change in runtime parameters of those
sub-algorithms sub-algorithms
*/ */
template<class Chrom> class eoEasyEA: public eoAlgo<Chrom> template<class Chrom> class eoEasyEA: public eoAlgo<Chrom>
{ {
public: public:
/// Constructor. /// Constructor.
eoEasyEA(eoBinPopOp<Chrom>& _select, eoEasyEA(eoBinPopOp<Chrom>& _select,
eoMonPopOp<Chrom>& _transform, eoMonPopOp<Chrom>& _transform,
eoBinPopOp<Chrom>& _replace, eoBinPopOp<Chrom>& _replace,
eoEvalFunc<Chrom>& _evaluator, eoEvalFunc<Chrom>& _evaluator,
eoTerm<Chrom>& _terminator) eoTerm<Chrom>& _terminator)
:step(_select, _transform, _replace, _evaluator), :step(_select, _transform, _replace, _evaluator),
terminator( _terminator){}; terminator( _terminator){};
/// Constructor from an already created generation /// Constructor from an already created generation
eoEasyEA(eoGeneration<Chrom>& _gen, eoEasyEA(eoGeneration<Chrom>& _gen,
eoTerm<Chrom>& _terminator): eoTerm<Chrom>& _terminator):
step(_gen), step(_gen),
terminator( _terminator){}; terminator( _terminator){};
/// Apply one generation of evolution to the population. /// Apply one generation of evolution to the population.
virtual void operator()(eoPop<Chrom>& pop) { virtual void operator()(eoPop<Chrom>& pop) {
while ( terminator( pop ) ) { while ( terminator( pop ) ) {
try try
{ {
step(pop); step(pop);
} }
catch (exception& e) catch (exception& e)
{ {
string s = e.what(); string s = e.what();
s.append( " in eoEasyEA "); s.append( " in eoEasyEA ");
throw runtime_error( s ); throw runtime_error( s );
} }
} // while } // while
} }
/// Class name. /// Class name.
string className() const { return "eoEasyEA"; } string className() const { return "eoEasyEA"; }
private: private:
eoGeneration<Chrom> step; eoGeneration<Chrom> step;
eoTerm<Chrom>& terminator; eoTerm<Chrom>& terminator;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif eoEasyEA_h #endif eoEasyEA_h

View file

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

View file

@ -1,69 +1,69 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoException.h eoException.h
Exceptions that are possibly thrown at initialization and such should be Exceptions that are possibly thrown at initialization and such should be
defined here defined here.
(c) GeNeura Team, 2000 (c) GeNeura Team, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoException_h #ifndef eoException_h
#define eoException_h #define eoException_h
#include <exception> #include <exception>
#include "eoObject.h" #include "eoObject.h"
struct eoException struct eoException
{ {
eoException() {} eoException() {}
eoException(const eoObject& caller) : who_caught_it(caller.className()) {} eoException(const eoObject& caller) : who_caught_it(caller.className()) {}
std::string who(void) const { return who_caught_it; } std::string who(void) const { return who_caught_it; }
virtual std::string what(void) const{ return "";} virtual std::string what(void) const{ return "";}
private : private :
std::string who_caught_it; std::string who_caught_it;
}; };
struct eoFitnessException : public eoException struct eoFitnessException : public eoException
{ {
eoFitnessException() : eoException() {} eoFitnessException() : eoException() {}
eoFitnessException(const eoObject& caller) : eoException(caller) {} eoFitnessException(const eoObject& caller) : eoException(caller) {}
}; };
struct eoNegativeFitnessException : public eoFitnessException struct eoNegativeFitnessException : public eoFitnessException
{ {
eoNegativeFitnessException() : eoFitnessException() {} eoNegativeFitnessException() : eoFitnessException() {}
eoNegativeFitnessException(const eoObject& caller) : eoFitnessException(caller) {} eoNegativeFitnessException(const eoObject& caller) : eoFitnessException(caller) {}
std::string what(void) const { return "negative fitness encountered"; } std::string what(void) const { return "negative fitness encountered"; }
}; };
struct eoMinimizingFitnessException : public eoFitnessException struct eoMinimizingFitnessException : public eoFitnessException
{ {
eoMinimizingFitnessException() : eoFitnessException() {} eoMinimizingFitnessException() : eoFitnessException() {}
eoMinimizingFitnessException(const eoObject& caller) : eoFitnessException(caller) {} eoMinimizingFitnessException(const eoObject& caller) : eoFitnessException(caller) {}
std::string what(void) const { return "smaller fitness is better fitness, which is quite inappropriate here"; } std::string what(void) const { return "smaller fitness is better fitness, which is quite inappropriate here"; }
}; };
#endif #endif

View file

@ -1,64 +1,65 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoGenTerm.h // eoGenTerm.h
// (c) GeNeura Team, 1999 // (c) GeNeura Team, 1999
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOFITTERM_H #ifndef _EOFITTERM_H
#define _EOFITTERM_H #define _EOFITTERM_H
#include <eoTerm.h> #include <eoTerm.h>
/** Fitness termination: terminates after a the difference between the /** Fitness termination: terminates after a the difference between the
fitness of the best individual and a maximum fitness to achieve is less fitness of the best individual and a maximum fitness to achieve is less
than certain number called epsilon., i.e., |maximum-fitness|<epsilon than certain number called epsilon., i.e., |maximum-fitness|<epsilon
*/ */
template< class EOT> template< class EOT>
class eoFitTerm: public eoTerm<EOT> { class eoFitTerm: public eoTerm<EOT> {
public: public:
/// Ctors/dtors /// Ctors/dtors
eoFitTerm( const float _maximum, const float _epsilon ) eoFitTerm( const float _maximum, const float _epsilon )
: eoTerm<EOT> (), maximum( _maximum ), epsilon(_epsilon){}; : eoTerm<EOT> (), maximum( _maximum ), epsilon(_epsilon){};
/// Copy ctor /// Copy ctor
eoFitTerm( const eoFitTerm& _t ) eoFitTerm( const eoFitTerm& _t )
: eoTerm<EOT> ( _t ), maximum( _t.maximum ), : eoTerm<EOT> ( _t ), maximum( _t.maximum ),
epsilon(_t.epsilon){}; epsilon(_t.epsilon){};
/// ///
virtual ~eoFitTerm() {}; virtual ~eoFitTerm() {};
/** Returns false when a certain number of generations is /** Returns false when a certain number of generations is
* reached */ * reached */
virtual bool operator() ( const eoPop<EOT>& _vEO ) { virtual bool operator() ( const eoPop<EOT>& _vEO ) {
float bestFitness=_vEO[0].fitness(); float bestFitness=_vEO[0].fitness();
float dif=bestFitness-maximum; float dif=bestFitness-maximum;
dif=(dif<0)?-dif:dif; dif=(dif<0)?-dif:dif;
return (dif>epsilon ) || (bestFitness > maximum); return (dif>epsilon ) || (bestFitness > maximum);
} }
private: private:
float maximum, epsilon; float maximum, epsilon;
}; };
#endif #endif

View file

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

View file

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

View file

@ -1,173 +1,174 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoGOpSelector.h eoGOpSelector.h
Base class for generalized (n-inputs, n-outputs) operator selectors. Base class for generalized (n-inputs, n-outputs) operator selectors.
Includes code and variables that contain operators and rates. Includes code and variables that contain operators and rates.
Also included eoProportionalGOpSelector and eoSequentialGOpSelector, that offer Also included eoProportionalGOpSelector and eoSequentialGOpSelector, that offer
a few concrete implementations. a few concrete implementations.
(c) Maarten Keijzer, GeNeura Team 1998, 1999, 2000 (c) Maarten Keijzer, GeNeura Team 1998, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoGOpSelector_h #ifndef eoGOpSelector_h
#define eoGOpSelector_h #define eoGOpSelector_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <list> #include <list>
#include "eoOpSelector.h" #include "eoOpSelector.h"
#include "eoWrappedOps.h" // for eoCombinedOp #include "eoWrappedOps.h" // for eoCombinedOp
#include "eoRNG.h" #include "eoRNG.h"
using namespace std; using namespace std;
/** Base class for alternative selectors, which use the generalized operator /** Base class for alternative selectors, which use the generalized operator
interface. eoGOpBreeders expects this class */ interface. eoGOpBreeders expects this class */
template<class EOT> template<class EOT>
class eoGOpSelector: public eoOpSelector<EOT>, public vector<eoGeneralOp<EOT>*> class eoGOpSelector: public eoOpSelector<EOT>, public vector<eoGeneralOp<EOT>*>
{ {
public: public:
typedef eoOpSelector<EOT>::ID ID; typedef eoOpSelector<EOT>::ID ID;
/// Dtor /// Dtor
virtual ~eoGOpSelector() { virtual ~eoGOpSelector() {
for ( list< eoGeneralOp<EOT>* >::iterator i= ownOpList.begin(); for ( list< eoGeneralOp<EOT>* >::iterator i= ownOpList.begin();
i != ownOpList.end(); i++ ) { i != ownOpList.end(); i++ ) {
delete *i; delete *i;
} }
} }
/// Add any kind of operator to the operator mix, with an argument /// Add any kind of operator to the operator mix, with an argument
virtual ID addOp( eoOp<EOT>& _op, float _arg ); virtual ID addOp( eoOp<EOT>& _op, float _arg );
// implementation can be found below // implementation can be found below
/** Retrieve the operator using its integer handle /** Retrieve the operator using its integer handle
@param _id The id number. Should be a valid id, or an exception @param _id The id number. Should be a valid id, or an exception
will be thrown will be thrown
@return a reference of the operator corresponding to that id. @return a reference of the operator corresponding to that id.
*/ */
virtual const eoOp<EOT>& getOp( ID _id ) virtual const eoOp<EOT>& getOp( ID _id )
{ {
return *operator[](_id); return *operator[](_id);
} }
/// ///
virtual void deleteOp( ID _id ); virtual void deleteOp( ID _id );
// implemented below // implemented below
/// ///
virtual eoOp<EOT>* Op() virtual eoOp<EOT>* Op()
{ {
return &selectOp(); return &selectOp();
} }
/// ///
virtual eoGeneralOp<EOT>& selectOp() = 0; virtual eoGeneralOp<EOT>& selectOp() = 0;
/// ///
virtual string className() const { return "eoGOpSelector"; }; virtual string className() const { return "eoGOpSelector"; };
/// ///
void printOn(ostream& _os) const {} void printOn(ostream& _os) const {}
// _os << className().c_str() << endl; // _os << className().c_str() << endl;
// for ( unsigned i=0; i!= rates.size(); i++ ) { // for ( unsigned i=0; i!= rates.size(); i++ ) {
// _os << *(operator[](i)) << "\t" << rates[i] << endl; // _os << *(operator[](i)) << "\t" << rates[i] << endl;
// } // }
//} //}
const vector<float>& getRates(void) const { return rates; } const vector<float>& getRates(void) const { return rates; }
private : private :
vector<float> rates; vector<float> rates;
list< eoGeneralOp<EOT>* > ownOpList; list< eoGeneralOp<EOT>* > ownOpList;
}; };
/* Implementation of longish functions defined above */ /* Implementation of longish functions defined above */
template <class EOT> template <class EOT>
inline eoOpSelector<EOT>::ID eoGOpSelector<EOT>::addOp( eoOp<EOT>& _op, float _arg ) inline eoOpSelector<EOT>::ID eoGOpSelector<EOT>::addOp( eoOp<EOT>& _op, float _arg )
{ {
eoGeneralOp<EOT>* op; eoGeneralOp<EOT>* op;
if (_op.getType() == eoOp<EOT>::general) if (_op.getType() == eoOp<EOT>::general)
{ {
op = static_cast<eoGeneralOp<EOT>*>(&_op); op = static_cast<eoGeneralOp<EOT>*>(&_op);
} }
else else
{ {
// if it's not a general op, it's a "old" op; create a wrapped op from it // 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 // and keep it on a list to delete them afterwards
// will use auto_ptr when they're readily available // will use auto_ptr when they're readily available
switch(_op.getType()) switch(_op.getType())
{ {
case eoOp<EOT>::unary : case eoOp<EOT>::unary :
op= new eoWrappedMonOp<EOT>(static_cast<eoMonOp<EOT>&>(_op)); op= new eoWrappedMonOp<EOT>(static_cast<eoMonOp<EOT>&>(_op));
break; break;
case eoOp<EOT>::binary : case eoOp<EOT>::binary :
op = new eoWrappedBinOp<EOT>(static_cast<eoBinOp<EOT>&>(_op)); op = new eoWrappedBinOp<EOT>(static_cast<eoBinOp<EOT>&>(_op));
case eoOp<EOT>::quadratic : case eoOp<EOT>::quadratic :
op = new eoWrappedQuadraticOp<EOT>(static_cast<eoQuadraticOp<EOT>&>(_op)); op = new eoWrappedQuadraticOp<EOT>(static_cast<eoQuadraticOp<EOT>&>(_op));
break; break;
} }
ownOpList.push_back( op ); ownOpList.push_back( op );
} }
// Now 'op' is a general operator, either because '_op' was one or // Now 'op' is a general operator, either because '_op' was one or
// because we wrapped it in an appropriate wrapper in the code above. // because we wrapped it in an appropriate wrapper in the code above.
iterator result = find(begin(), end(), (eoGeneralOp<EOT>*) 0); // search for nullpointer iterator result = find(begin(), end(), (eoGeneralOp<EOT>*) 0); // search for nullpointer
if (result == end()) if (result == end())
{ {
push_back(op); push_back(op);
rates.push_back(_arg); rates.push_back(_arg);
return size(); return size();
} }
// else // else
*result = op; *result = op;
ID id = result - begin(); ID id = result - begin();
rates[id] = _arg; rates[id] = _arg;
return id; return id;
} }
template <class EOT> template <class EOT>
inline void eoGOpSelector<EOT>::deleteOp( ID _id ) inline void eoGOpSelector<EOT>::deleteOp( ID _id )
{ {
eoGeneralOp<EOT>* op = operator[](_id); eoGeneralOp<EOT>* op = operator[](_id);
operator[](_id) = 0; operator[](_id) = 0;
rates[_id] = 0.0; rates[_id] = 0.0;
// check oplist and clear it there too. // check oplist and clear it there too.
list< eoGeneralOp<EOT>* >::iterator it = find(ownOpList.begin(), ownOpList.end(), op); list< eoGeneralOp<EOT>* >::iterator it = find(ownOpList.begin(), ownOpList.end(), op);
if(it != ownOpList.end()) if(it != ownOpList.end())
{ {
ownOpList.erase(it); ownOpList.erase(it);
} }
} }
#endif eoGOpSelector_h #endif eoGOpSelector_h

View file

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

View file

@ -1,109 +1,110 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoID.h // eoID.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef EOID_H #ifndef EOID_H
#define EOID_H #define EOID_H
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <iostream> // istream, ostream #include <iostream> // istream, ostream
#include <string> // for string #include <string> // for string
using namespace std; using namespace std;
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoID // eoID
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** eoID is a template class that adds an ID to an object.\\ /** 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 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, 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.\\ 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. IDs can be used to count objects of a a kind, or track them, or whatever.
@see eoObject @see eoObject
*/ */
template <class Object> template <class Object>
class eoID: public Object class eoID: public Object
{ {
public: public:
/// Main ctor from an already built Object. /// Main ctor from an already built Object.
eoID( const Object& _o): Object( _o ), thisID(globalID++) {}; eoID( const Object& _o): Object( _o ), thisID(globalID++) {};
/// Copy constructor. /// Copy constructor.
eoID( const eoID& _id): Object( _id ), thisID(globalID++ ) {}; eoID( const eoID& _id): Object( _id ), thisID(globalID++ ) {};
/// Virtual dtor. They are needed in virtual class hierarchies /// Virtual dtor. They are needed in virtual class hierarchies
virtual ~eoID() {}; virtual ~eoID() {};
///returns the age of the object ///returns the age of the object
unsigned long ID() const {return thisID;} unsigned long ID() const {return thisID;}
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d readFrom and printOn are directly inherited from eo1d
*/ */
//@{ //@{
/** Return the class id. This should be redefined in each class; but /** Return the class id. This should be redefined in each class; but
it's got code as an example of implementation. Only "leaf" classes it's got code as an example of implementation. Only "leaf" classes
can be non-virtual. can be non-virtual.
*/ */
virtual string className() const { return string("[eoID]")+Object::className(); }; virtual string className() const { return string("[eoID]")+Object::className(); };
/** /**
* Read object. * Read object.
* @param _is A istream. * @param _is A istream.
* @throw runtime_exception If a valid object can't be read. * @throw runtime_exception If a valid object can't be read.
*/ */
virtual void readFrom(istream& _is) { virtual void readFrom(istream& _is) {
Object::readFrom( _is ); Object::readFrom( _is );
_is >> thisID; _is >> thisID;
} }
/** /**
* Write object. It's called printOn since it prints the object _on_ a stream. * Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream. * @param _os A ostream.
*/ */
virtual void printOn(ostream& _os) const{ virtual void printOn(ostream& _os) const{
Object::printOn( _os ); Object::printOn( _os );
_os << thisID; _os << thisID;
} }
//@} //@}
private: private:
/** Default Constructor. \\ /** Default Constructor. \\
It´s private so that it is not used anywhere; the right way of using this object 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 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*/ it´s turned into an Aged object*/
eoID(): Object(), thisID( globalID++ ) {}; eoID(): Object(), thisID( globalID++ ) {};
unsigned long thisID; unsigned long thisID;
static unsigned long globalID; static unsigned long globalID;
}; };
template< class Object> template< class Object>
unsigned long eoID< Object >::globalID = 0; unsigned long eoID< Object >::globalID = 0;
#endif EOID_H #endif EOID_H

View file

@ -1,134 +1,134 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoIndiSelector.h eoIndiSelector.h
Abstract selection operator, which is used by the eoGeneralOps Abstract selection operator, which is used by the eoGeneralOps
to obtain individuals from a source population. It also gives a to obtain individuals from a source population. It also gives a
direct descended eoPopIndiSelector that can be used to direct descended eoPopIndiSelector that can be used to
initialize objects with an eoPop<EOT>. For most uses use eoPopIndividualSelector initialize objects with an eoPop<EOT>. For most uses use eoPopIndividualSelector
rather than eoIndividualSelector to derive from. rather than eoIndividualSelector to derive from.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoIndiSelector_h #ifndef eoIndiSelector_h
#define eoIndiSelector_h #define eoIndiSelector_h
/** /**
* eoIndividualSelector: This class defines the interface * eoIndividualSelector: This class defines the interface
*/ */
template <class EOT> template <class EOT>
class eoIndiSelector class eoIndiSelector
{ {
public : public :
eoIndiSelector() {} eoIndiSelector() {}
virtual ~eoIndiSelector(void) {} virtual ~eoIndiSelector(void) {}
virtual size_t size(void) const = 0; virtual size_t size(void) const = 0;
virtual const EOT& operator[](size_t) const = 0; virtual const EOT& operator[](size_t) const = 0;
virtual const EOT& select(void) = 0; virtual const EOT& select(void) = 0;
virtual vector<const EOT*> select(size_t _how_many) virtual vector<const EOT*> select(size_t _how_many)
{ // default implementation just calls select a couple of times { // default implementation just calls select a couple of times
// this can be overridden in favour of a more efficient implementation // this can be overridden in favour of a more efficient implementation
vector<const EOT*> result(_how_many); vector<const EOT*> result(_how_many);
for (int i = 0; i < _how_many; ++i) for (int i = 0; i < _how_many; ++i)
{ {
result[i] = &select(); result[i] = &select();
} }
return result; return result;
} }
}; };
/** /**
* eoPopIndiSelector: Intermediate class for dispensing populations * eoPopIndiSelector: Intermediate class for dispensing populations
various useful things can be done with this class: various useful things can be done with this class:
you can specify how many of the population can ever be dispensed to the 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 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 dispensed. This is useful if you want to perform the operator on a specific
individual. individual.
*/ */
template <class EOT> template <class EOT>
class eoPopIndiSelector : public eoIndiSelector<EOT> class eoPopIndiSelector : public eoIndiSelector<EOT>
{ {
public : public :
eoPopIndiSelector(void) : pop(0), firstChoice(-1), last(0), eoIndiSelector<EOT>() {} eoPopIndiSelector(void) : pop(0), firstChoice(-1), last(0), eoIndiSelector<EOT>() {}
virtual ~eoPopIndiSelector(void) {} virtual ~eoPopIndiSelector(void) {}
struct eoUnitializedException{}; struct eoUnitializedException{};
/** Initialization function /** Initialization function
*/ */
eoPopIndiSelector& operator()(const eoPop<EOT>& _pop, int _end = -1, int _myGuy = -1) eoPopIndiSelector& operator()(const eoPop<EOT>& _pop, int _end = -1, int _myGuy = -1)
{ {
pop = &_pop; pop = &_pop;
last = _end; last = _end;
if (last < 0 || last > pop->size()) if (last < 0 || last > pop->size())
{ {
last = pop->size(); last = pop->size();
} }
firstChoice = _myGuy; firstChoice = _myGuy;
return *this; return *this;
} }
size_t size(void) const { valid(); return last; } size_t size(void) const { valid(); return last; }
const EOT& operator[](size_t _i) const { valid(); return pop->operator[](_i); } 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 begin(void) const { valid(); return pop->begin(); }
eoPop<EOT>::const_iterator end(void) const { valid(); return pop->end(); } 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 /// 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) const EOT& select(void)
{ {
valid(); valid();
if (firstChoice < 0 || firstChoice >= size()) if (firstChoice < 0 || firstChoice >= size())
{ {
return do_select(); // let the child figure out what to do return do_select(); // let the child figure out what to do
} }
const EOT& result = pop->operator[](firstChoice); const EOT& result = pop->operator[](firstChoice);
firstChoice = -1; firstChoice = -1;
return result; return result;
} }
virtual const EOT& do_select(void) = 0; virtual const EOT& do_select(void) = 0;
private : private :
void valid(void) const void valid(void) const
{ {
if (pop == 0) if (pop == 0)
throw eoUnitializedException(); throw eoUnitializedException();
} }
const eoPop<EOT>* pop; // need a pointer as this the pop argument can be re-instated const eoPop<EOT>* pop; // need a pointer as this the pop argument can be re-instated
int last; int last;
int firstChoice; int firstChoice;
}; };
#endif #endif

View file

@ -1,92 +1,93 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoInserter.h eoInserter.h
Abstract population insertion operator, which is used by the eoGeneralOps Abstract population insertion operator, which is used by the eoGeneralOps
to insert the results in the (intermediate) population. It also contains to insert the results in the (intermediate) population. It also contains
a direct descended eoPopInserter that defines a convenient inbetween class a direct descended eoPopInserter that defines a convenient inbetween class
for working with eoPop<EOT>. The user will most likely derive from eoPopInserter for working with eoPop<EOT>. The user will most likely derive from eoPopInserter
rather than eoInserter. rather than eoInserter.
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoInserter_h #ifndef eoInserter_h
#define eoInserter_h #define eoInserter_h
#include "eoPop.h" #include "eoPop.h"
/** /**
* eoInserter: Interface class that enables an operator to insert * eoInserter: Interface class that enables an operator to insert
new individuals into the (intermediate) population. new individuals into the (intermediate) population.
*/ */
template <class EOT> template <class EOT>
class eoInserter : public eoObject class eoInserter : public eoObject
{ {
public : public :
virtual ~eoInserter() {} virtual ~eoInserter() {}
struct eoInserterException{}; struct eoInserterException{};
virtual void insert(const EOT&) = 0; // can throw an eoInserterException virtual void insert(const EOT&) = 0; // can throw an eoInserterException
}; };
/** /**
* eoPopInserter: In-between class that defines an initialization * eoPopInserter: In-between class that defines an initialization
* of the eoIndividualInserter. * of the eoIndividualInserter.
*/ */
template <class EOT> template <class EOT>
class eoPopInserter : public eoInserter<EOT> class eoPopInserter : public eoInserter<EOT>
{ {
public : public :
eoPopInserter(void) : thePop(0), eoInserter<EOT>() {} eoPopInserter(void) : thePop(0), eoInserter<EOT>() {}
/// Binds the population to this class. This is an initialization routine used by breeders /// Binds the population to this class. This is an initialization routine used by breeders
eoInserter<EOT>& operator()(eoPop<EOT>& _pop) eoInserter<EOT>& operator()(eoPop<EOT>& _pop)
{ {
thePop = &_pop; thePop = &_pop;
return *this; return *this;
} }
protected : protected :
eoPop<EOT>& pop(void) const { valid(); return *thePop; } eoPop<EOT>& pop(void) const { valid(); return *thePop; }
private : private :
void valid(void) const void valid(void) const
{ {
if (thePop == 0) if (thePop == 0)
throw eoInserterException(); throw eoInserterException();
} }
// Need a pointer as the inserter should be able to bind to different populations. // 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. // This is caused by the 'one template parameter only' convention in EO.
eoPop<EOT>* thePop; eoPop<EOT>* thePop;
// If eoGOpBreeder could be templatized over the inserter and the selector, // 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 // 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 // and subsequently would get the population through the constructor
}; };
#endif #endif

View file

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

View file

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

View file

@ -1,99 +1,100 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoMultiBinOp.h // eoMultiBinOp.h
// Class that combines several binary or unary operators // Class that combines several binary or unary operators
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOMULTIBINOP_h #ifndef _EOMULTIBINOP_h
#define _EOMULTIBINOP_h #define _EOMULTIBINOP_h
#include <iterator> #include <iterator>
#include <eoOp.h> #include <eoOp.h>
/** MultiMonOp combines several monary operators. By itself, it does nothing to the /** MultiMonOp combines several monary operators. By itself, it does nothing to the
EO it´s handled*/ EO it´s handled*/
template <class EOT> template <class EOT>
class eoMultiBinOp: public eoBinOp<EOT> { class eoMultiBinOp: public eoBinOp<EOT> {
public: public:
/// Ctor from an already existing op /// Ctor from an already existing op
eoMultiBinOp( const eoBinOp<EOT>* _op ) eoMultiBinOp( const eoBinOp<EOT>* _op )
: eoBinOp< EOT >( ), vOp(){ : eoBinOp< EOT >( ), vOp(){
vOp.push_back( _op ); vOp.push_back( _op );
}; };
/// ///
eoMultiBinOp( ) eoMultiBinOp( )
: eoBinOp< EOT >( ), vOp(){}; : eoBinOp< EOT >( ), vOp(){};
/// Ads a new operator /// Ads a new operator
void adOp( const eoOp<EOT>* _op ){ void adOp( const eoOp<EOT>* _op ){
vOp.push_back( _op ); vOp.push_back( _op );
}; };
/// needed virtual dtor /// needed virtual dtor
virtual ~eoMultiBinOp() {}; virtual ~eoMultiBinOp() {};
/// ///
/// Applies all operators to the EO /// Applies all operators to the EO
virtual void operator()( EOT& _eo1, EOT& _eo2 ) const { virtual void operator()( EOT& _eo1, EOT& _eo2 ) const {
if ( vOp.begin() != vOp.end() ) { // which would mean it's empty if ( vOp.begin() != vOp.end() ) { // which would mean it's empty
for ( vector< const eoOp<EOT>* >::const_iterator i = vOp.begin(); for ( vector< const eoOp<EOT>* >::const_iterator i = vOp.begin();
i != vOp.end(); i++ ) { i != vOp.end(); i++ ) {
// Admits only unary or binary operator // Admits only unary or binary operator
switch ((*i)->readArity()) { switch ((*i)->readArity()) {
case unary: case unary:
{ {
const eoMonOp<EOT>* monop = static_cast<const eoMonOp<EOT>* >(*i); const eoMonOp<EOT>* monop = static_cast<const eoMonOp<EOT>* >(*i);
(*monop)( _eo1 ); (*monop)( _eo1 );
(*monop)( _eo2 ); (*monop)( _eo2 );
break; break;
} }
case binary: case binary:
{ {
const eoBinOp<EOT>* binop = static_cast<const eoBinOp<EOT>* >(*i); const eoBinOp<EOT>* binop = static_cast<const eoBinOp<EOT>* >(*i);
(*binop)( _eo1, _eo2 ); (*binop)( _eo1, _eo2 );
break; break;
} }
} }
} }
} }
} }
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp readFrom and printOn are directly inherited from eoOp
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
string className() const {return "eoMultiBinOp";}; string className() const {return "eoMultiBinOp";};
//@} //@}
private: private:
/// uses pointers to base class since operators can be unary or binary /// uses pointers to base class since operators can be unary or binary
vector< const eoOp<EOT>* > vOp; vector< const eoOp<EOT>* > vOp;
}; };
#endif #endif

View file

@ -1,80 +1,80 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoMultiMonOp.h // eoMultiMonOp.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOMULTIMONOP_h #ifndef _EOMULTIMONOP_h
#define _EOMULTIMONOP_h #define _EOMULTIMONOP_h
#include <iterator> #include <iterator>
#include <eoOp.h> #include <eoOp.h>
/** MultiMonOp combines several monary operators. By itself, it does nothing to the /** MultiMonOp combines several monary operators. By itself, it does nothing to the
EO it´s handled*/ EO it´s handled*/
template <class EOT> template <class EOT>
class eoMultiMonOp: public eoMonOp<EOT> { class eoMultiMonOp: public eoMonOp<EOT> {
public: public:
/// Ctor from an already existing op /// Ctor from an already existing op
eoMultiMonOp( const eoMonOp<EOT>* _op ) eoMultiMonOp( const eoMonOp<EOT>* _op )
: eoMonOp< EOT >( ), vOp(){ : eoMonOp< EOT >( ), vOp(){
vOp.push_back( _op ); vOp.push_back( _op );
}; };
/// ///
eoMultiMonOp( ) eoMultiMonOp( )
: eoMonOp< EOT >( ), vOp(){}; : eoMonOp< EOT >( ), vOp(){};
/// Ctor from an already existing op /// Ctor from an already existing op
void adOp( const eoMonOp<EOT>* _op ){ void adOp( const eoMonOp<EOT>* _op ){
vOp.push_back( _op ); vOp.push_back( _op );
}; };
/// needed virtual dtor /// needed virtual dtor
virtual ~eoMultiMonOp() {}; virtual ~eoMultiMonOp() {};
/// ///
/// Applies all operators to the EO /// Applies all operators to the EO
virtual void operator()( EOT& _eo ) const { virtual void operator()( EOT& _eo ) const {
if ( vOp.begin() != vOp.end() ) { if ( vOp.begin() != vOp.end() ) {
for ( vector<const eoMonOp<EOT>* >::const_iterator i = vOp.begin(); for ( vector<const eoMonOp<EOT>* >::const_iterator i = vOp.begin();
i != vOp.end(); i++ ) { i != vOp.end(); i++ ) {
(*i)->operator () ( _eo ); (*i)->operator () ( _eo );
} }
} }
} }
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp readFrom and printOn are directly inherited from eoOp
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
string className() const {return "eoMonOp";}; string className() const {return "eoMonOp";};
//@} //@}
private: private:
vector< const eoMonOp<EOT>* > vOp; vector< const eoMonOp<EOT>* > vOp;
}; };
#endif #endif

View file

@ -1,90 +1,91 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoMutation.h // eoMutation.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOMUTATION_H #ifndef _EOMUTATION_H
#define _EOMUTATION_H #define _EOMUTATION_H
#include <math.h> #include <math.h>
// EO includes // EO includes
#include <eoOp.h> #include <eoOp.h>
#include <eoUniform.h> #include <eoUniform.h>
/** Generic Mutation of an EO. /** Generic Mutation of an EO.
This is a virtual class, just to establish the interface for the ctor. This is a virtual class, just to establish the interface for the ctor.
Mutation is usually type-specific Mutation is usually type-specific
*/ */
template <class EOT> template <class EOT>
class eoMutation: public eoMonOp<EOT> { class eoMutation: public eoMonOp<EOT> {
public: public:
/// ///
eoMutation(const double _rate=0.0) : eoMonOp< EOT >(), rate(_rate) {}; eoMutation(const double _rate=0.0) : eoMonOp< EOT >(), rate(_rate) {};
/// ///
virtual ~eoMutation() {}; virtual ~eoMutation() {};
/// ///
virtual void operator()( EOT& _eo ) const { virtual void operator()( EOT& _eo ) const {
typename EOT::iterator i; typename EOT::iterator i;
for ( i = _eo.begin(); i != _eo.end(); i ++ ) for ( i = _eo.begin(); i != _eo.end(); i ++ )
applyAt( _eo, *i ); applyAt( _eo, *i );
} }
/// To print me on a stream. /// To print me on a stream.
/// @param os The ostream. /// @param os The ostream.
void printOn(ostream& os) const { void printOn(ostream& os) const {
os << rate ; os << rate ;
} }
/// To read me from a stream. /// To read me from a stream.
/// @param is The istream. /// @param is The istream.
void readFrom(istream& is) { void readFrom(istream& is) {
is >> rate ; is >> rate ;
} }
/** @name Methods from eoObject /** @name Methods from eoObject
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
string className() const {return "eoMutation";}; string className() const {return "eoMutation";};
//@} //@}
protected: protected:
double rate; double rate;
private: private:
#ifdef _MSC_VER #ifdef _MSC_VER
typedef EOT::Type Type; typedef EOT::Type Type;
#else #else
typedef typename EOT::Type Type; typedef typename EOT::Type Type;
#endif #endif
/// applies operator to one gene in the EO. It is empty, so each descent class must define it. /// 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 ; virtual void applyAt( EOT& _eo, unsigned _i ) const = 0 ;
}; };
#endif #endif

View file

@ -1,66 +1,67 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoNegExp.h eoNegExp.h
(c) GeNeura Team, 1998 (c) GeNeura Team, 1998
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EONEGEXP_H #ifndef _EONEGEXP_H
#define _EONEGEXP_H #define _EONEGEXP_H
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <math.h> #include <math.h>
#include <eoRnd.h> // for base class #include <eoRnd.h> // for base class
#include <eoRNG.h> // for base class #include <eoRNG.h> // for base class
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Class eoNegExp // Class eoNegExp
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/// Generates random numbers using a negative exponential distribution /// Generates random numbers using a negative exponential distribution
template<class T> template<class T>
class eoNegExp: public eoRnd<T> class eoNegExp: public eoRnd<T>
{ {
public: public:
/** /**
* Default constructor. * Default constructor.
* @param _mean Distribution mean * @param _mean Distribution mean
*/ */
eoNegExp(T _mean): eoRnd<T>(), mean(_mean) {}; eoNegExp(T _mean): eoRnd<T>(), mean(_mean) {};
/** /**
* Copy constructor. * Copy constructor.
* @param _rnd the copyee * @param _rnd the copyee
*/ */
eoNegExp( const eoNegExp& _rnd): eoRnd<T>( _rnd), mean(_rnd.mean) {}; eoNegExp( const eoNegExp& _rnd): eoRnd<T>( _rnd), mean(_rnd.mean) {};
/// Returns an uniform dandom number over the interval [min, max). /// Returns an uniform dandom number over the interval [min, max).
virtual T operator()() { virtual T operator()() {
return T( -mean*log((double)rng.rand() / rng.rand_max())); } return T( -mean*log((double)rng.rand() / rng.rand_max())); }
private: private:
T mean; T mean;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif #endif

View file

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

View file

@ -1,88 +1,89 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoNormal.h // eoNormal.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EONORMAL_H #ifndef _EONORMAL_H
#define _EONORMAL_H #define _EONORMAL_H
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <math.h> #include <math.h>
#include <eoRnd.h> // for base class #include <eoRnd.h> // for base class
#include <eoRNG.h> // for random number generator #include <eoRNG.h> // for random number generator
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Class eoNormal // Class eoNormal
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/// Generates random number using a normal distribution /// Generates random number using a normal distribution
template<class T> template<class T>
class eoNormal: public eoRnd<T> class eoNormal: public eoRnd<T>
{ {
public: public:
/** /**
* Default constructor. * Default constructor.
* @param _mean Dsitribution mean * @param _mean Dsitribution mean
* @param _sd Standard Deviation * @param _sd Standard Deviation
*/ */
eoNormal(T _mean, T _sd) eoNormal(T _mean, T _sd)
: eoRnd<T>(), mean(_mean), sd(_sd), phase(false) {} : eoRnd<T>(), mean(_mean), sd(_sd), phase(false) {}
/** /**
* Copy constructor. * Copy constructor.
* @param _rnd the other one * @param _rnd the other one
*/ */
eoNormal( const eoNormal& _rnd ) eoNormal( const eoNormal& _rnd )
: eoRnd<T>( _rnd), mean(_rnd.mean), sd(_rnd.sd), phase(false) {} : eoRnd<T>( _rnd), mean(_rnd.mean), sd(_rnd.sd), phase(false) {}
/** Returns an uniform random number over the interval [min, max). /** Returns an uniform random number over the interval [min, max).
@return an uniform random number over the interval [min, max). @return an uniform random number over the interval [min, max).
*/ */
virtual T operator()() { virtual T operator()() {
if (phase) { // Already have one stored up. if (phase) { // Already have one stored up.
phase = false; phase = false;
return T ( (sqRatio * q * sd) + mean ); return T ( (sqRatio * q * sd) + mean );
} }
double p, v; double p, v;
do { do {
p = ((double)rng.rand() / rng.rand_max())*2-1; p = ((double)rng.rand() / rng.rand_max())*2-1;
q = ((double)rng.rand() / rng.rand_max())*2-1; q = ((double)rng.rand() / rng.rand_max())*2-1;
v = p*p + q*q; v = p*p + q*q;
} while(v > 1.0 || v <0.25); } while(v > 1.0 || v <0.25);
sqRatio = sqrt(-2*log((double)rand() / rng.rand_max()) / v); sqRatio = sqrt(-2*log((double)rand() / rng.rand_max()) / v);
phase = true; phase = true;
return T( (sqRatio * p * sd) + mean ); return T( (sqRatio * p * sd) + mean );
}; };
private: private:
T mean; T mean;
T sd; T sd;
bool phase; bool phase;
double sqRatio, q; double sqRatio, q;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif #endif

View file

@ -1,68 +1,69 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoObject.h // eoObject.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef EOOBJECT_H #ifndef EOOBJECT_H
#define EOOBJECT_H #define EOOBJECT_H
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <eoData.h> // For limits definition #include <eoData.h> // For limits definition
#include <iostream> // istream, ostream #include <iostream> // istream, ostream
#include <string> // string #include <string> // string
#include "compatibility.h" #include "compatibility.h"
using namespace std; using namespace std;
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoObject // eoObject
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** /**
This is the base class for the whole hierarchy; an eoObject defines This is the base class for the whole hierarchy; an eoObject defines
basically an interface for the whole hierarchy: each object should basically an interface for the whole hierarchy: each object should
know its name (#className#). Previously, this object defined a print and read know its name (#className#). Previously, this object defined a print and read
interface, but it´s been moved to eoPrintable and eoPersistent. interface, but it´s been moved to eoPrintable and eoPersistent.
*/ */
class eoObject class eoObject
{ {
public: public:
/// Default Constructor. /// Default Constructor.
eoObject() {} eoObject() {}
/// Copy constructor. /// Copy constructor.
eoObject( const eoObject& ) {} eoObject( const eoObject& ) {}
/// Virtual dtor. They are needed in virtual class hierarchies. /// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoObject() {} virtual ~eoObject() {}
/** Return the class id. This should be redefined in each class; but /** Return the class id. This should be redefined in each class; but
it's got code as an example of implementation. Only "leaf" classes it's got code as an example of implementation. Only "leaf" classes
can be non-virtual. can be non-virtual.
*/ */
virtual string className() const { return "eoObject"; } virtual string className() const { return "eoObject"; }
}; };
#endif EOOBJECT_H #endif EOOBJECT_H

View file

@ -1,235 +1,236 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoOp.h // eoOp.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _eoOp_H #ifndef _eoOp_H
#define _eoOp_H #define _eoOp_H
#include <eoObject.h> #include <eoObject.h>
#include <eoPrintable.h> #include <eoPrintable.h>
/** @name Genetic operators /** @name Genetic operators
What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with 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) 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, as siblings). Nobody should subclass eoOp, you should subclass eoGeneralOp, eoBinOp, eoQuadraticOp or eoMonOp,
those are the ones actually used here.\\ 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 #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 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. factory, which know how to build them from a description in a file.
@author GeNeura Team @author GeNeura Team
@version 0.1 @version 0.1
@see eoOpFactory @see eoOpFactory
*/ */
/** Abstract data types for EO operators. /** Abstract data types for EO operators.
* Genetic operators act on chromosomes, changing them. The type to instantiate them should * 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 * be an eoObject, but in any case, they are type-specific; each kind of evolvable object
* can have its own operators * can have its own operators
*/ */
template<class EOType> template<class EOType>
class eoOp: public eoObject, public eoPrintable { class eoOp: public eoObject, public eoPrintable {
public: public:
//@{ //@{
enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3}; enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3};
/// ///
/// Ctor /// Ctor
eoOp(OpType _type) eoOp(OpType _type)
:opType( _type ) {}; :opType( _type ) {};
/// Copy Ctor /// Copy Ctor
eoOp( const eoOp& _eop ) eoOp( const eoOp& _eop )
:opType( _eop.opType ) {}; :opType( _eop.opType ) {};
/// Needed virtual destructor /// Needed virtual destructor
virtual ~eoOp(){}; virtual ~eoOp(){};
/// getType: number of operands it takes and individuals it produces /// getType: number of operands it takes and individuals it produces
OpType getType() const {return opType;}; OpType getType() const {return opType;};
/** @name Methods from eoObject */ /** @name Methods from eoObject */
//@{ //@{
/** /**
* Write object. It's called printOn since it prints the object _on_ a stream. * Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream. * @param _os A ostream.
*/ */
virtual void printOn(ostream& _os) const { virtual void printOn(ostream& _os) const {
_os << className().c_str(); _os << className().c_str();
// _os << arity; // _os << arity;
}; };
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoOp";}; virtual string className() const {return "eoOp";};
//@} //@}
private: private:
/// OpType is the type of the operator: how many operands it takes and how many it produces /// OpType is the type of the operator: how many operands it takes and how many it produces
OpType opType; OpType opType;
}; };
/** Binary genetic operator: subclasses eoOp, and defines /** Binary genetic operator: subclasses eoOp, and defines
basically the operator() with two operands basically the operator() with two operands
*/ */
template<class EOType> template<class EOType>
class eoBinOp: public eoOp<EOType> { class eoBinOp: public eoOp<EOType> {
public: public:
/// Ctor /// Ctor
eoBinOp() eoBinOp()
:eoOp<EOType>( binary ) {}; :eoOp<EOType>( binary ) {};
/// Copy Ctor /// Copy Ctor
eoBinOp( const eoBinOp& _ebop ) eoBinOp( const eoBinOp& _ebop )
: eoOp<EOType>( _ebop ){}; : eoOp<EOType>( _ebop ){};
/// Dtor /// Dtor
~eoBinOp () {}; ~eoBinOp () {};
/** applies operator, to the object. Modifies only the first operand. /** applies operator, to the object. Modifies only the first operand.
*/ */
virtual void operator()( EOType& _eo1, const EOType& _eo2 ) const = 0; virtual void operator()( EOType& _eo1, const EOType& _eo2 ) const = 0;
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject readFrom and printOn are directly inherited from eoObject
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoBinOp";}; virtual string className() const {return "eoBinOp";};
//@} //@}
}; };
/** Quadratic genetic operator: subclasses eoOp, and defines /** Quadratic genetic operator: subclasses eoOp, and defines
basically the operator() with two operands basically the operator() with two operands
*/ */
template<class EOType> template<class EOType>
class eoQuadraticOp: public eoOp<EOType> { class eoQuadraticOp: public eoOp<EOType> {
public: public:
/// Ctor /// Ctor
eoQuadraticOp() eoQuadraticOp()
:eoOp<EOType>( eoOp<EOType>::quadratic ) {}; :eoOp<EOType>( eoOp<EOType>::quadratic ) {};
/// Copy Ctor /// Copy Ctor
eoQuadraticOp( const eoQuadraticOp& _ebop ) eoQuadraticOp( const eoQuadraticOp& _ebop )
: eoOp<EOType>( _ebop ){}; : eoOp<EOType>( _ebop ){};
/// Dtor /// Dtor
~eoQuadraticOp() {}; ~eoQuadraticOp() {};
/** applies operator, to the object. Modifies both operands. /** applies operator, to the object. Modifies both operands.
*/ */
virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0;
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject readFrom and printOn are directly inherited from eoObject
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoBinOp";}; virtual string className() const {return "eoBinOp";};
//@} //@}
}; };
/** eoMonOp is the monary operator: genetic operator that takes /** eoMonOp is the monary operator: genetic operator that takes
only one EO only one EO
*/ */
template <class EOType> template <class EOType>
class eoMonOp: public eoOp<EOType> { class eoMonOp: public eoOp<EOType> {
public: public:
/// Ctor /// Ctor
eoMonOp( ) eoMonOp( )
: eoOp<EOType>( eoOp<EOType>::unary ) {}; : eoOp<EOType>( eoOp<EOType>::unary ) {};
/// Copy Ctor /// Copy Ctor
eoMonOp( const eoMonOp& _emop ) eoMonOp( const eoMonOp& _emop )
: eoOp<EOType>( _emop ){}; : eoOp<EOType>( _emop ){};
/// Dtor /// Dtor
~eoMonOp() {}; ~eoMonOp() {};
/** applies randomly operator, to the object. If arity is more than 1, /** applies randomly operator, to the object. If arity is more than 1,
* keeps a copy of the operand in a cache. * keeps a copy of the operand in a cache.
*/ */
virtual void operator()( EOType& _eo1) const = 0; virtual void operator()( EOType& _eo1) const = 0;
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject readFrom and printOn are directly inherited from eoObject
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoMonOp";}; virtual string className() const {return "eoMonOp";};
//@} //@}
}; };
// some forward declarations // some forward declarations
template<class EOT> template<class EOT>
class eoIndiSelector; class eoIndiSelector;
template<class EOT> template<class EOT>
class eoInserter; class eoInserter;
/** /**
* eGeneralOp: General genetic operator; for objects used to transform sets * eGeneralOp: General genetic operator; for objects used to transform sets
of EOs. Nary ("orgy") operators should be derived from this class of EOs. Nary ("orgy") operators should be derived from this class
*/ */
template<class EOT> template<class EOT>
class eoGeneralOp: public eoOp<EOT> class eoGeneralOp: public eoOp<EOT>
{ {
public: public:
/// Ctor that honors its superclass /// Ctor that honors its superclass
eoGeneralOp(): eoOp<EOT>( eoOp<EOT>::general ) {}; eoGeneralOp(): eoOp<EOT>( eoOp<EOT>::general ) {};
/// Virtual dtor /// Virtual dtor
virtual ~eoGeneralOp () {}; virtual ~eoGeneralOp () {};
/** Method that really does the stuff. Applies the genetic operator /** Method that really does the stuff. Applies the genetic operator
to a individuals dispensed by an eoIndividualSelector, to a individuals dispensed by an eoIndividualSelector,
and puts the results in the eoIndividualInserter. and puts the results in the eoIndividualInserter.
Any number of inputs can be requested and any number of outputs Any number of inputs can be requested and any number of outputs
can be produced. can be produced.
*/ */
virtual void operator()( eoIndiSelector<EOT>& _in, virtual void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const = 0; eoInserter<EOT>& _out) const = 0;
virtual string className() const {return "eoGeneralOp";}; virtual string className() const {return "eoGeneralOp";};
}; };
#endif #endif

View file

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

View file

@ -1,70 +1,74 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- 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 // eoPersistent.h
modify it under the terms of the GNU Lesser General Public // (c) GeNeura Team, 1999
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
This library is distributed in the hope that it will be useful, License as published by the Free Software Foundation; either
but WITHOUT ANY WARRANTY; without even the implied warranty of version 2 of the License, or (at your option) any later version.
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
You should have received a copy of the GNU Lesser General Public MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
License along with this library; if not, write to the Free Software Lesser General Public License for more details.
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
You should have received a copy of the GNU Lesser General Public
Contact: todos@geneura.ugr.es, http://geneura.ugr.es 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 #ifndef EOPERSISTENT_H
//@{ #define EOPERSISTENT_H
/// max length to store stuff read
const unsigned MAXLINELENGTH=1024; /// @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 <iostream> // istream, ostream
#include <eoPrintable.h> #include <string> // para string
using namespace std; //-----------------------------------------------------------------------------
#include <eoPrintable.h>
//-----------------------------------------------------------------------------
// eoPersistent using namespace std;
//-----------------------------------------------------------------------------
/** //-----------------------------------------------------------------------------
An persistent object that knows how to write (through functions inherited from // eoPersistent
#eoPrintable#) and read itself //-----------------------------------------------------------------------------
*/ /**
class eoPersistent: public eoPrintable An persistent object that knows how to write (through functions inherited from
{ #eoPrintable#) and read itself
public: */
/// Virtual dtor. They are needed in virtual class hierarchies. class eoPersistent: public eoPrintable
virtual ~eoPersistent() {} {
public:
/** /// Virtual dtor. They are needed in virtual class hierarchies.
* Read object. virtual ~eoPersistent() {}
* @param _is A istream.
* @throw runtime_exception If a valid object can't be read. /**
*/ * Read object.
virtual void readFrom(istream& _is) = 0; * @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 ///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; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoPop.h // eoPop.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOPOP_H #ifndef _EOPOP_H
#define _EOPOP_H #define _EOPOP_H
#include <vector> #include <vector>
#include <strstream> #include <strstream>
// EO includes // EO includes
#include <eoRnd.h> #include <eoRnd.h>
#include <eoPersistent.h> #include <eoPersistent.h>
#include <eoEvalFunc.h> #include <eoEvalFunc.h>
/** Subpopulation: it is used to move parts of population /** Subpopulation: it is used to move parts of population
from one algorithm to another and one population to another. It is safer 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 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 some other thing that a vector, but if somebody thinks of it, this concrete
implementation will be moved to "generic" and an abstract Population implementation will be moved to "generic" and an abstract Population
interface will be provided. interface will be provided.
It can be instantiated with anything, provided that it accepts a "size" and a 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 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 so far. EOT must also have a copy ctor, since temporaries are created and copied
to the population. to the population.
@author Geneura Team @author Geneura Team
@version 0.0 @version 0.0
*/ */
template<class EOT> template<class EOT>
class eoPop: public vector<EOT>, public eoObject, public eoPersistent { class eoPop: public vector<EOT>, public eoObject, public eoPersistent {
/// Type is the type of each gene in the chromosome /// Type is the type of each gene in the chromosome
#ifdef _MSC_VER #ifdef _MSC_VER
typedef EOT::Type Type; typedef EOT::Type Type;
#else #else
typedef typename EOT::Type Type; typedef typename EOT::Type Type;
#endif #endif
public: public:
/** Protected ctor. This is intended to avoid creation of void populations, except /** Protected ctor. This is intended to avoid creation of void populations, except
from sibling classes from sibling classes
*/ */
eoPop() :vector<EOT>() {}; eoPop() :vector<EOT>() {};
/** Ctor for fixed-size chromosomes, with variable content /** Ctor for fixed-size chromosomes, with variable content
@param _popSize total population size @param _popSize total population size
@param _eoSize chromosome size. EOT should accept a fixed-size ctor @param _eoSize chromosome size. EOT should accept a fixed-size ctor
@param _geneRdn random number generator for each of the genes @param _geneRdn random number generator for each of the genes
*/ */
eoPop( unsigned _popSize, unsigned _eoSize, eoRnd<Type> & _geneRnd ) eoPop( unsigned _popSize, unsigned _eoSize, eoRnd<Type> & _geneRnd )
:vector<EOT>() { :vector<EOT>() {
for ( unsigned i = 0; i < _popSize; i ++ ){ for ( unsigned i = 0; i < _popSize; i ++ ){
EOT tmpEOT( _eoSize, _geneRnd); EOT tmpEOT( _eoSize, _geneRnd);
push_back( tmpEOT ); push_back( tmpEOT );
} }
}; };
/** Ctor for variable-size chromosomes, with variable content /** Ctor for variable-size chromosomes, with variable content
@param _popSize total population size @param _popSize total population size
@param _sizeRnd RNG for the chromosome size. This will be added 1, just in case. @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 @param _geneRdn random number generator for each of the genes
*/ */
eoPop( unsigned _popSize, eoRnd<unsigned> & _sizeRnd, eoRnd<Type> & _geneRnd ) eoPop( unsigned _popSize, eoRnd<unsigned> & _sizeRnd, eoRnd<Type> & _geneRnd )
:vector<EOT>() { :vector<EOT>() {
for ( unsigned i = 0; i < _popSize; i ++ ){ for ( unsigned i = 0; i < _popSize; i ++ ){
unsigned size = 1 + _sizeRnd(); unsigned size = 1 + _sizeRnd();
EOT tmpEOT( size, _geneRnd); EOT tmpEOT( size, _geneRnd);
push_back( tmpEOT ); push_back( tmpEOT );
} }
}; };
/** Ctor for fixed-size chromosomes, with variable content /** Ctor for fixed-size chromosomes, with variable content
@param _popSize total population size @param _popSize total population size
@param _eoSize chromosome size. EOT should accept a fixed-size ctor @param _eoSize chromosome size. EOT should accept a fixed-size ctor
@param _geneRdn random number generator for each of the genes @param _geneRdn random number generator for each of the genes
*/ */
eoPop( unsigned _popSize, unsigned _eoSize, eoRnd<Type> & _geneRnd, eoEvalFunc<EOT>& _eval) eoPop( unsigned _popSize, unsigned _eoSize, eoRnd<Type> & _geneRnd, eoEvalFunc<EOT>& _eval)
:vector<EOT>() { :vector<EOT>() {
for ( unsigned i = 0; i < _popSize; i ++ ){ for ( unsigned i = 0; i < _popSize; i ++ ){
EOT tmpEOT( _eoSize, _geneRnd); EOT tmpEOT( _eoSize, _geneRnd);
push_back( tmpEOT ); push_back( tmpEOT );
_eval(back()); _eval(back());
} }
}; };
/** Ctor from an istream; reads the population from a stream, /** Ctor from an istream; reads the population from a stream,
each element should be in different lines each element should be in different lines
@param _is the stream @param _is the stream
*/ */
eoPop( istream& _is ):vector<EOT>() { eoPop( istream& _is ):vector<EOT>() {
readFrom( _is ); readFrom( _is );
} }
/// ///
~eoPop() {}; ~eoPop() {};
/** @name Methods from eoObject */ /** @name Methods from eoObject */
//@{ //@{
/** /**
* Read object. The EOT class must have a ctor from a stream; * Read object. The EOT class must have a ctor from a stream;
in this case, a strstream is used. in this case, a strstream is used.
* @param _is A istream. * @param _is A istream.
*/ */
virtual void readFrom(istream& _is) { virtual void readFrom(istream& _is) {
while( _is ) { // reads line by line, and creates an object per while( _is ) { // reads line by line, and creates an object per
// line // line
char line[MAXLINELENGTH]; char line[MAXLINELENGTH];
_is.getline( line, MAXLINELENGTH-1 ); _is.getline( line, MAXLINELENGTH-1 );
if (strlen( line ) ) { if (strlen( line ) ) {
istrstream s( line ); istrstream s( line );
EOT thisEOT( s ); EOT thisEOT( s );
push_back( thisEOT ); push_back( thisEOT );
} }
} }
} }
/** /**
* Write object. It's called printOn since it prints the object _on_ a stream. * 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 * @param _os A ostream. In this case, prints the population to
standard output. The EOT class must hav standard output with cout, standard output. The EOT class must hav standard output with cout,
but since it should be an eoObject anyways, it's no big deal. but since it should be an eoObject anyways, it's no big deal.
*/ */
virtual void printOn(ostream& _os) const { virtual void printOn(ostream& _os) const {
copy( begin(), end(), ostream_iterator<EOT>( _os, "\n") ); copy( begin(), end(), ostream_iterator<EOT>( _os, "\n") );
}; };
/** Inherited from eoObject. Returns the class name. /** Inherited from eoObject. Returns the class name.
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoPop";}; virtual string className() const {return "eoPop";};
//@} //@}
protected: protected:
}; };
#endif #endif

View file

@ -1,62 +1,63 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoPrintable.h // eoPrintable.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef EOPRINTABLE_H #ifndef EOPRINTABLE_H
#define EOPRINTABLE_H #define EOPRINTABLE_H
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <iostream> // istream, ostream #include <iostream> // istream, ostream
#include <string> // para string #include <string> // para string
using namespace std; using namespace std;
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoPrintable // eoPrintable
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** /**
Base class for objects that can print themselves Base class for objects that can print themselves
(#printOn#). Besides, this file defines the standard output for all the objects; (#printOn#). Besides, this file defines the standard output for all the objects;
if the objects define printOn there's no need to define #operator <<#.\\ 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 This functionality was separated from eoObject, since it makes no sense to print
some objects (for instance, a #eoFactory# or a random number generator. some objects (for instance, a #eoFactory# or a random number generator.
*/ */
class eoPrintable class eoPrintable
{ {
public: public:
/// Virtual dtor. They are needed in virtual class hierarchies. /// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoPrintable() {} virtual ~eoPrintable() {}
/** /**
* Write object. It's called printOn since it prints the object on a stream. * Write object. It's called printOn since it prints the object on a stream.
* @param _os A ostream. * @param _os A ostream.
*/ */
virtual void printOn(ostream& _os) const = 0; virtual void printOn(ostream& _os) const = 0;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
///Standard output for all objects in the EO hierarchy ///Standard output for all objects in the EO hierarchy
ostream & operator << ( ostream& _os, const eoPrintable& _o ); ostream & operator << ( ostream& _os, const eoPrintable& _o );
#endif EOPRINTABLE_H #endif EOPRINTABLE_H

View file

@ -1,40 +1,45 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoProblem.h
// (c) GeNeura Team 1998 // eoProblem.h
/*
This library is free software; you can redistribute it and/or // (c) GeNeura Team 1998
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
This library is distributed in the hope that it will be useful, modify it under the terms of the GNU Lesser General Public
but WITHOUT ANY WARRANTY; without even the implied warranty of License as published by the Free Software Foundation; either
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU version 2 of the License, or (at your option) any later version.
Lesser General Public License for more details.
This library is distributed in the hope that it will be useful,
You should have received a copy of the GNU Lesser General Public but WITHOUT ANY WARRANTY; without even the implied warranty of
License along with this library; if not, write to the Free Software MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Lesser General Public License for more details.
Contact: todos@geneura.ugr.es, http://geneura.ugr.es 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
#ifndef EOPROBLEM_H Contact: todos@geneura.ugr.es, http://geneura.ugr.es
#define EOPROBLEM_H */
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifndef EOPROBLEM_H
template<class T> class Problem #define EOPROBLEM_H
{
public: //-----------------------------------------------------------------------------
typedef T Chrom;
typedef typename T::Gene Gene; template<class T> class Problem
typedef typename T::Fitness Fitness; {
public:
virtual Fitness operator()(const Chrom& chrom) = 0; typedef T Chrom;
}; typedef typename T::Gene Gene;
typedef typename T::Fitness Fitness;
//-----------------------------------------------------------------------------
virtual Fitness operator()(const Chrom& chrom) = 0;
#endif EOPROBLEM_H };
//-----------------------------------------------------------------------------
#endif EOPROBLEM_H

View file

@ -1,54 +1,55 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoProportionalGOpSelector.h eoProportionalGOpSelector.h
Proportional Generalized Operator Selector. Proportional Generalized Operator Selector.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000 (c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoProportionalGOpSelector_h #ifndef eoProportionalGOpSelector_h
#define eoProportionalGOpSelector_h #define eoProportionalGOpSelector_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include "eoGOpSelector.h" #include "eoGOpSelector.h"
/** eoProportionalGOpSel: do proportional selection, returns one of the /** eoProportionalGOpSel: do proportional selection, returns one of the
operators operators
*/ */
template <class EOT> template <class EOT>
class eoProportionalGOpSel : public eoGOpSelector<EOT> class eoProportionalGOpSel : public eoGOpSelector<EOT>
{ {
public : public :
eoProportionalGOpSel() : eoGOpSelector<EOT>() {} eoProportionalGOpSel() : eoGOpSelector<EOT>() {}
/** Returns the operator proportionally selected */ /** Returns the operator proportionally selected */
virtual eoGeneralOp<EOT>& selectOp() virtual eoGeneralOp<EOT>& selectOp()
{ {
unsigned what = rng.roulette_wheel(getRates()); unsigned what = rng.roulette_wheel(getRates());
return *operator[](what); return *operator[](what);
} }
/// ///
virtual string className() const { return "eoGOpSelector"; }; virtual string className() const { return "eoGOpSelector"; };
}; };
#endif #endif

View file

@ -1,154 +1,159 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- 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 // eoProportionalOpSel.h
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either // (c) GeNeura Team 1998
version 2 of the License, or (at your option) any later version. /*
This library is free software; you can redistribute it and/or
This library is distributed in the hope that it will be useful, modify it under the terms of the GNU Lesser General Public
but WITHOUT ANY WARRANTY; without even the implied warranty of License as published by the Free Software Foundation; either
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU version 2 of the License, or (at your option) any later version.
Lesser General Public License for more details.
This library is distributed in the hope that it will be useful,
You should have received a copy of the GNU Lesser General Public but WITHOUT ANY WARRANTY; without even the implied warranty of
License along with this library; if not, write to the Free Software MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Lesser General Public License for more details.
Contact: todos@geneura.ugr.es, http://geneura.ugr.es 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
#ifndef EOPROPORTIONALOPSEL_H Contact: todos@geneura.ugr.es, http://geneura.ugr.es
#define EOPROPORTIONALOPSEL_H */
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifndef EOPROPORTIONALOPSEL_H
#include <stdexcept> // runtime_error #define EOPROPORTIONALOPSEL_H
#include <functional> // greater
#include <map> //-----------------------------------------------------------------------------
// Includes from EO #include <stdexcept> // runtime_error
#include <eoUniform.h> #include <functional> // greater
#include <eoOpSelector.h> #include <map>
#include <eoOp.h>
// Includes from EO
//----------------------------------------------------------------------------- #include <eoUniform.h>
/** This class selects operators according to probability. All operator percentages #include <eoOpSelector.h>
should add up to one; if not, an exception will be raised.\\ #include <eoOp.h>
Operators are represented as pairs (proportion,operator)
*/ //-----------------------------------------------------------------------------
template<class EOT> /** This class selects operators according to probability. All operator percentages
class eoProportionalOpSel: public eoOpSelector<EOT>, should add up to one; if not, an exception will be raised.\\
public multimap<float,eoOp<EOT>*,greater<float> > Operators are represented as pairs (proportion,operator)
{ */
public: template<class EOT>
class eoProportionalOpSel: public eoOpSelector<EOT>,
typedef multimap<float, eoOp<EOT>*,greater<float> > MMF; public multimap<float,eoOp<EOT>*,greater<float> >
{
/// default ctor public:
eoProportionalOpSel()
: eoOpSelector<EOT>(), MMF(), opID(1) {}; typedef multimap<float, eoOp<EOT>*,greater<float> > MMF;
/// virtual dtor /// default ctor
virtual ~eoProportionalOpSel() {}; eoProportionalOpSel()
: eoOpSelector<EOT>(), MMF(), opID(1) {};
/** Gets a non-const reference to an operator, so that it can be changed,
modified or whatever /// virtual dtor
@param _id a previously assigned ID virtual ~eoProportionalOpSel() {};
@throw runtime_error if the ID does not exist*/
/** Gets a non-const reference to an operator, so that it can be changed,
virtual eoOp<EOT>& getOp( ID _id ) { modified or whatever
MMF::iterator i=begin(); @param _id a previously assigned ID
ID j = 1; @throw runtime_error if the ID does not exist*/
while ( (i++!=end()) && (j++ != _id) );
if ( i == end() ) virtual eoOp<EOT>& getOp( ID _id ) {
throw runtime_error( "No such id in eoProportionalOpSel::op\n" ); MMF::iterator i=begin();
return *(i->second); ID j = 1;
//return i->second; while ( (i++!=end()) && (j++ != _id) );
} if ( i == end() )
throw runtime_error( "No such id in eoProportionalOpSel::op\n" );
/** add an operator to the operator set return *(i->second);
@param _op a genetic operator, that will be applied in some way //return i->second;
@param _arg an argument to the operator, usually operator rate }
@return an ID that will be used to identify the operator
*/ /** add an operator to the operator set
virtual ID addOp( eoOp<EOT>& _op, float _arg ) { @param _op a genetic operator, that will be applied in some way
insert( MMF::value_type( _arg,& _op ) ); @param _arg an argument to the operator, usually operator rate
return opID++; @return an ID that will be used to identify the operator
} */
virtual ID addOp( eoOp<EOT>& _op, float _arg ) {
/** Remove an operator from the operator set insert( MMF::value_type( _arg,& _op ) );
@param _id a previously assigned ID return opID++;
@throw runtime_error if the ID does not exist }
*/
virtual void deleteOp( ID _id ) { /** Remove an operator from the operator set
unsigned j; @param _id a previously assigned ID
MMF::iterator i; @throw runtime_error if the ID does not exist
for ( i=begin(), j=1; i!=end(); i++,j++ ) { */
if( j == _id ) virtual void deleteOp( ID _id ) {
erase( i ); unsigned j;
return; MMF::iterator i;
} for ( i=begin(), j=1; i!=end(); i++,j++ ) {
if ( i == end() ) if( j == _id )
throw runtime_error( "No such id in eoProportionalOpSel::op\n" ); erase( i );
}; return;
}
/// Returns a genetic operator according to the established criteria if ( i == end() )
virtual eoOp<EOT>* Op() { throw runtime_error( "No such id in eoProportionalOpSel::op\n" );
// Check that all add up to one };
float acc = 0;
MMF::iterator i; /// Returns a genetic operator according to the established criteria
unsigned j; virtual eoOp<EOT>* Op() {
for ( i=begin(), j=1; i!=end(); i++,j++ ) { // Check that all add up to one
acc +=i->first; float acc = 0;
} MMF::iterator i;
if ( acc != 1.0 ) unsigned j;
throw runtime_error( "Operator rates added up different from 1.0" ); for ( i=begin(), j=1; i!=end(); i++,j++ ) {
acc +=i->first;
// If here, operators ordered by rate and no problem }
eoUniform<float> u(0,1.0); if ( acc != 1.0 )
float aRnd = u(); throw runtime_error( "Operator rates added up different from 1.0" );
i=begin();
acc = 0; // If here, operators ordered by rate and no problem
do { eoUniform<float> u(0,1.0);
acc += i->first; float aRnd = u();
} while ( (acc <= aRnd ) && (i++!=end() ) ); i=begin();
if ( i == end() ) acc = 0;
throw runtime_error( "Operator not found in eoProportionalOpSelector" ); do {
return i->second; acc += i->first;
//return i->second; } while ( (acc <= aRnd ) && (i++!=end() ) );
} if ( i == end() )
throw runtime_error( "Operator not found in eoProportionalOpSelector" );
/// Methods inherited from eoObject return i->second;
//@{ //return i->second;
}
/** Return the class id.
@return the class name as a string /// Methods inherited from eoObject
*/ //@{
virtual string className() const { return "eoProportionalOpSel"; };
/** Return the class id.
/** Print itself: inherited from eoObject implementation. Declared virtual so that @return the class name as a string
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. virtual string className() const { return "eoProportionalOpSel"; };
@param _s the ostream in which things are written*/
virtual void printOn( ostream& _s ) const{ /** Print itself: inherited from eoObject implementation. Declared virtual so that
_s << className().c_str() << endl; it can be reimplemented anywhere. Instance from base classes are processed in
for ( MMF::const_iterator i=begin(); i!=end(); i++ ) { base classes, so you don´t have to worry about, for instance, fitness.
_s << i->first << "\t" << *(i->second )<< endl; @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;
}; //@}
//----------------------------------------------------------------------------- private:
ID opID;
#endif EO_H };
//-----------------------------------------------------------------------------
#endif EO_H

View file

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

View file

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

View file

@ -1,61 +1,62 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoSequentialGOpSelector.h eoSequentialGOpSelector.h
Sequential Generalized Operator Selector. Sequential Generalized Operator Selector.
(c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000 (c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoSequentialGOpSelector_h #ifndef eoSequentialGOpSelector_h
#define eoSequentialGOpSelector_h #define eoSequentialGOpSelector_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include "eoGOpSelector.h" #include "eoGOpSelector.h"
/** eoSequentialGOpSel: do proportional selection, but return a sequence of /** eoSequentialGOpSel: do proportional selection, but return a sequence of
operations to be applied one after the other. operations to be applied one after the other.
*/ */
template <class EOT> template <class EOT>
class eoSequentialGOpSel : public eoGOpSelector<EOT> class eoSequentialGOpSel : public eoGOpSelector<EOT>
{ {
public : public :
virtual eoGeneralOp<EOT>& selectOp() virtual eoGeneralOp<EOT>& selectOp()
{ {
combined.clear(); combined.clear();
for (int i = 0; i < size(); ++i) for (int i = 0; i < size(); ++i)
{ {
if (operator[](i) == 0) if (operator[](i) == 0)
continue; continue;
if (rng.flip(getRates()[i])) if (rng.flip(getRates()[i]))
combined.addOp(operator[](i)); combined.addOp(operator[](i));
} }
return combined; return combined;
} }
private : private :
eoCombinedOp<EOT> combined; eoCombinedOp<EOT> combined;
}; };
#endif #endif

View file

@ -1,86 +1,87 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoSteadyStateEA.h // eoSteadyStateEA.h
// (c) GeNeura Team, 2000 // (c) GeNeura Team, 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _eoSteadyStateEA_h #ifndef _eoSteadyStateEA_h
#define _eoSteadyStateEA_h #define _eoSteadyStateEA_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include "eoSteadyStateGeneration.h" // eoPop #include "eoSteadyStateGeneration.h" // eoPop
#include <eoTerm.h> #include <eoTerm.h>
/** EOSteadyStateEA: /** EOSteadyStateEA:
An easy-to-use evolutionary algorithm, just supply An easy-to-use evolutionary algorithm, just supply
a general operator selector, a selector for choosing the ones a general operator selector, a selector for choosing the ones
to reproduce and an eoSteadyStateInserter that takes care of evaluating to reproduce and an eoSteadyStateInserter that takes care of evaluating
and inserter the guy/girl in the steady state population. and inserter the guy/girl in the steady state population.
*/ */
template<class EOT> class eoSteadyStateEA: public eoAlgo<EOT> template<class EOT> class eoSteadyStateEA: public eoAlgo<EOT>
{ {
public: public:
/// Constructor. /// Constructor.
eoSteadyStateEA( eoSteadyStateEA(
eoGOpSelector<EOT>& _opSelector, eoGOpSelector<EOT>& _opSelector,
eoPopIndiSelector<EOT>& _selector, eoPopIndiSelector<EOT>& _selector,
eoSteadyStateInserter<EOT>& _inserter, eoSteadyStateInserter<EOT>& _inserter,
eoTerm<EOT>& _terminator, eoTerm<EOT>& _terminator,
unsigned _steps = 0 ) unsigned _steps = 0 )
: step(_opSelector, _selector, _inserter), : step(_opSelector, _selector, _inserter),
terminator( _terminator) terminator( _terminator)
{}; {};
/// Constructor from an already created generation /// Constructor from an already created generation
eoSteadyStateEA(eoSteadyStateGeneration<EOT>& _gen, eoSteadyStateEA(eoSteadyStateGeneration<EOT>& _gen,
eoTerm<EOT>& _terminator): eoTerm<EOT>& _terminator):
step(_gen), step(_gen),
terminator( _terminator){}; terminator( _terminator){};
/// Apply one generation of evolution to the population. /// Apply one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop) { virtual void operator()(eoPop<EOT>& pop) {
do { do {
try try
{ {
step(pop); step(pop);
} }
catch (exception& e) catch (exception& e)
{ {
string s = e.what(); string s = e.what();
s.append( " in eoSteadyStateEA "); s.append( " in eoSteadyStateEA ");
throw runtime_error( s ); throw runtime_error( s );
} }
} while ( terminator( pop ) ); } while ( terminator( pop ) );
} }
/// Class name. /// Class name.
string className() const { return "eoSteadyStateEA"; } string className() const { return "eoSteadyStateEA"; }
private: private:
eoSteadyStateGeneration<EOT> step; eoSteadyStateGeneration<EOT> step;
eoTerm<EOT>& terminator; eoTerm<EOT>& terminator;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif eoEasyEA_h #endif eoEasyEA_h

View file

@ -1,88 +1,89 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoSteadyStateGeneration.h // eoSteadyStateGeneration.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoSteadyStateGeneration_h #ifndef eoSteadyStateGeneration_h
#define eoSteadyStateGeneration_h #define eoSteadyStateGeneration_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <eoAlgo.h> // eoPop #include <eoAlgo.h> // eoPop
#include <eoEvalFunc.h> #include <eoEvalFunc.h>
#include <eoPopOps.h> // eoSelect, eoTranform, eoMerge #include <eoPopOps.h> // eoSelect, eoTranform, eoMerge
#include "eoGOpSelector.h" #include "eoGOpSelector.h"
#include "eoIndiSelector.h" #include "eoIndiSelector.h"
#include "eoSteadyStateInserter.h" #include "eoSteadyStateInserter.h"
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** eoSteadyStateGeneration /** eoSteadyStateGeneration
* Single step of a steady state evolutionary algorithm. * Single step of a steady state evolutionary algorithm.
* Proceeds by updating one individual at a time, by first selecting parents, * Proceeds by updating one individual at a time, by first selecting parents,
* creating one or more children and subsequently overwrite (a) bad individual(s) * creating one or more children and subsequently overwrite (a) bad individual(s)
*/ */
template<class EOT> class eoSteadyStateGeneration: public eoAlgo<EOT> template<class EOT> class eoSteadyStateGeneration: public eoAlgo<EOT>
{ {
public: public:
/// Constructor. /// Constructor.
eoSteadyStateGeneration( eoSteadyStateGeneration(
eoGOpSelector<EOT>& _opSelector, eoGOpSelector<EOT>& _opSelector,
eoPopIndiSelector<EOT>& _selector, eoPopIndiSelector<EOT>& _selector,
eoSteadyStateInserter<EOT>& _inserter, eoSteadyStateInserter<EOT>& _inserter,
unsigned _steps = 0) : unsigned _steps = 0) :
opSelector(_opSelector), opSelector(_opSelector),
selector(_selector), selector(_selector),
inserter(_inserter) , inserter(_inserter) ,
steps(_steps) {}; steps(_steps) {};
/// Apply one generation of evolution to the population. /// Apply one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop) virtual void operator()(eoPop<EOT>& pop)
{ {
unsigned nSteps = steps; unsigned nSteps = steps;
if (nSteps == 0) if (nSteps == 0)
{ {
nSteps = pop.size(); // make a 'generation equivalent' nSteps = pop.size(); // make a 'generation equivalent'
} }
for (unsigned i = 0; i < nSteps; ++i) for (unsigned i = 0; i < nSteps; ++i)
{ {
opSelector.selectOp()(selector(pop), inserter(pop)); opSelector.selectOp()(selector(pop), inserter(pop));
} }
} }
/// Class name. /// Class name.
string className() const { return "eoSteadyStateGeneration"; } string className() const { return "eoSteadyStateGeneration"; }
private: private:
eoGOpSelector<EOT>& opSelector; eoGOpSelector<EOT>& opSelector;
eoPopIndiSelector<EOT>& selector; eoPopIndiSelector<EOT>& selector;
eoSteadyStateInserter<EOT>& inserter; eoSteadyStateInserter<EOT>& inserter;
unsigned steps; unsigned steps;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif eoGeneration_h #endif eoGeneration_h

View file

@ -1,51 +1,51 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoSteadyStateInserter.h eoSteadyStateInserter.h
Still abstract population insertion operator that is initialized with Still abstract population insertion operator that is initialized with
and eoEvalFunc object to be able to evaluate individuals before inserting and eoEvalFunc object to be able to evaluate individuals before inserting
them. them.
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoSteadyStateInserter_h #ifndef eoSteadyStateInserter_h
#define eoSteadyStateInserter_h #define eoSteadyStateInserter_h
#include "eoEvalFunc.h" #include "eoEvalFunc.h"
/** /**
* eoSteadyStateInserter: Interface class that enables an operator to update * eoSteadyStateInserter: Interface class that enables an operator to update
* a population with a new individual... it contains an eoEvalFunc object to * a population with a new individual... it contains an eoEvalFunc object to
* make sure that every individual is evaluated before it is inserted * make sure that every individual is evaluated before it is inserted
*/ */
template <class EOT> template <class EOT>
class eoSteadyStateInserter : public eoPopInserter<EOT> class eoSteadyStateInserter : public eoPopInserter<EOT>
{ {
public : public :
eoSteadyStateInserter(eoEvalFunc<EOT>& _eval) : eval(_eval) , eoPopInserter<EOT>() {} eoSteadyStateInserter(eoEvalFunc<EOT>& _eval) : eval(_eval) , eoPopInserter<EOT>() {}
protected : protected :
eoEvalFunc<EOT>& eval; eoEvalFunc<EOT>& eval;
}; };
#endif #endif

View file

@ -1,68 +1,69 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoStochTournament.h // eoStochTournament.h
// (c) GeNeura Team, 1998 - EEAAX 1999 // (c) GeNeura Team, 1998 - EEAAX 1999
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoStochTournament_h #ifndef eoStochTournament_h
#define eoStochTournament_h #define eoStochTournament_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <functional> // #include <functional> //
#include <numeric> // accumulate #include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT #include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h> #include <eoRNG.h>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** eoStochTournament: a selection method that selects ONE individual by /** eoStochTournament: a selection method that selects ONE individual by
binary stochastic tournament binary stochastic tournament
-MS- 24/10/99 */ -MS- 24/10/99 */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
template <class EOT> class eoStochTournament: public eoSelectOne<EOT> template <class EOT> class eoStochTournament: public eoSelectOne<EOT>
{ {
public: public:
/// ///
eoStochTournament(float _Trate = 1.0 ):eoSelectOne<EOT>(), Trate(_Trate) { eoStochTournament(float _Trate = 1.0 ):eoSelectOne<EOT>(), Trate(_Trate) {
// consistency check // consistency check
if (Trate < 0.5) { if (Trate < 0.5) {
cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n"; cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n";
Trate = 0.55; Trate = 0.55;
} }
} }
/** DANGER: if you want to be able to minimize as well as maximizem /** 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! */ DON'T cast the fitness to a float, use the EOT comparator! */
virtual const EOT& operator()(const eoPop<EOT>& pop) virtual const EOT& operator()(const eoPop<EOT>& pop)
{ {
return stochastic_tournament(pop, Trate)(); return stochastic_tournament(pop, Trate)();
} }
private: private:
float Trate; float Trate;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif eoDetTournament_h #endif eoDetTournament_h

View file

@ -1,73 +1,73 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoStochTournamentInserter.h eoStochTournamentInserter.h
Concrete steady state inserter. It is initialized with a population and Concrete steady state inserter. It is initialized with a population and
inserts individuals in the population based on an inverse stochastic inserts individuals in the population based on an inverse stochastic
tournament tournament
(c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoStochTournamentInserter_h #ifndef eoStochTournamentInserter_h
#define eoStochTournamentInserter_h #define eoStochTournamentInserter_h
#include "eoSteadyStateInserter.h" #include "eoSteadyStateInserter.h"
#include "selectors.h" #include "selectors.h"
/** /**
* eoDetTournamentInserter: Uses an inverse stochastic tournament to figure * eoDetTournamentInserter: Uses an inverse stochastic tournament to figure
* out who gets overridden by the new individual. It resets the fitness of the * out who gets overridden by the new individual. It resets the fitness of the
* individual. * individual.
*/ */
template <class EOT> template <class EOT>
class eoStochTournamentInserter : public eoSteadyStateInserter<EOT> class eoStochTournamentInserter : public eoSteadyStateInserter<EOT>
{ {
public : public :
eoStochTournamentInserter(eoEvalFunc<EOT>& _eval, double _t_rate) : t_rate(_t_rate), eoSteadyStateInserter<EOT>(_eval) eoStochTournamentInserter(eoEvalFunc<EOT>& _eval, double _t_rate) : t_rate(_t_rate), eoSteadyStateInserter<EOT>(_eval)
{ {
if (t_rate < 0.5) if (t_rate < 0.5)
{ // warning, error? { // warning, error?
t_rate = 0.55; t_rate = 0.55;
} }
if (t_rate >= 1.0) if (t_rate >= 1.0)
{ {
t_rate = 0.99; // 1.0 would mean deterministic tournament t_rate = 0.99; // 1.0 would mean deterministic tournament
} }
} }
void insert(const EOT& _eot) void insert(const EOT& _eot)
{ {
EOT& eo = inverse_stochastic_tournament<EOT>(pop(), t_rate); EOT& eo = inverse_stochastic_tournament<EOT>(pop(), t_rate);
eo = _eot; // overwrite loser of tournament eo = _eot; // overwrite loser of tournament
eo.invalidate(); eo.invalidate();
eval(eo); // Evaluate after insert eval(eo); // Evaluate after insert
} }
string className(void) const { return "eoStochTournamentInserter"; } string className(void) const { return "eoStochTournamentInserter"; }
private : private :
double t_rate; double t_rate;
}; };
#endif #endif

View file

@ -1,147 +1,148 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoString.h // eoString.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _eoString_H #ifndef _eoString_H
#define _eoString_H #define _eoString_H
// STL libraries // STL libraries
#include <string> #include <string>
#include <stdexcept> #include <stdexcept>
using namespace std; using namespace std;
// EO headers // EO headers
#include <eo1d.h> #include <eo1d.h>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoString // eoString
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** Adaptor that turns an STL string into an EO */ /** Adaptor that turns an STL string into an EO */
template <class fitnessT > template <class fitnessT >
class eoString: public eo1d<char, fitnessT>, public string { class eoString: public eo1d<char, fitnessT>, public string {
public: public:
/// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator /// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator
//@{ //@{
/// ctor /// ctor
eoString( const string& _str ="" ) eoString( const string& _str ="" )
: eo1d<char, fitnessT>(), string( _str ) {}; : eo1d<char, fitnessT>(), string( _str ) {};
/** Ctor using a random number generator /** Ctor using a random number generator
@param _size Lineal length of the object @param _size Lineal length of the object
@param _rnd a random number generator, which returns a random value each time it´s called @param _rnd a random number generator, which returns a random value each time it´s called
*/ */
eoString( unsigned _size, eoRnd<char>& _rnd ) eoString( unsigned _size, eoRnd<char>& _rnd )
: eo1d<char, fitnessT>(), string(){ : eo1d<char, fitnessT>(), string(){
for ( unsigned i = 0; i < _size; i ++ ) { for ( unsigned i = 0; i < _size; i ++ ) {
*this += _rnd(); *this += _rnd();
} }
}; };
/** Ctor from a stream /** Ctor from a stream
@param _s input stream @param _s input stream
*/ */
eoString( istream & _s ) eoString( istream & _s )
: eo1d<char, fitnessT>(){ : eo1d<char, fitnessT>(){
_s >> *this; _s >> *this;
}; };
/// copy ctor /// copy ctor
eoString( const eoString<fitnessT>& _eoStr ) eoString( const eoString<fitnessT>& _eoStr )
:eo1d<char, fitnessT>( static_cast<const eo1d<char, fitnessT> & > ( _eoStr ) ), :eo1d<char, fitnessT>( static_cast<const eo1d<char, fitnessT> & > ( _eoStr ) ),
string( _eoStr ){}; string( _eoStr ){};
/// Assignment operator /// Assignment operator
const eoString& operator =( const eoString& _eoStr ) { const eoString& operator =( const eoString& _eoStr ) {
if ( this != & _eoStr ) { if ( this != & _eoStr ) {
eo1d<char, fitnessT>::operator = ( _eoStr ); eo1d<char, fitnessT>::operator = ( _eoStr );
string::operator = ( _eoStr ); string::operator = ( _eoStr );
} }
return *this; return *this;
} }
/// dtor /// dtor
virtual ~eoString() {}; virtual ~eoString() {};
//@} //@}
/** methods that implement the eo1d <em>protocol</em> /** methods that implement the eo1d <em>protocol</em>
@exception out_of_range if _i is larger than EO´s size @exception out_of_range if _i is larger than EO´s size
*/ */
virtual char getGene( unsigned _i ) const { virtual char getGene( unsigned _i ) const {
if ( _i >= length() ) if ( _i >= length() )
throw out_of_range( "out_of_range when reading gene"); throw out_of_range( "out_of_range when reading gene");
return (*this)[_i]; return (*this)[_i];
}; };
/** methods that implement the eo1d <em>protocol</em> /** methods that implement the eo1d <em>protocol</em>
@exception out_of_range if _i is larger than EO´s size @exception out_of_range if _i is larger than EO´s size
*/ */
virtual void setGene( unsigned _i, const char& _value ) { virtual void setGene( unsigned _i, const char& _value ) {
if ( _i >= size() ) if ( _i >= size() )
throw out_of_range( "out_of_range when writing a gene"); throw out_of_range( "out_of_range when writing a gene");
(*this)[_i] = _value; (*this)[_i] = _value;
}; };
/** Inserts a value after _i, displacing anything to the right /** Inserts a value after _i, displacing anything to the right
@exception out_of_range if _i is larger than EO´s size @exception out_of_range if _i is larger than EO´s size
*/ */
virtual void insertGene( unsigned _i, char _val ) { virtual void insertGene( unsigned _i, char _val ) {
if (_i <= this->size() ) { if (_i <= this->size() ) {
string::iterator i = this->begin()+_i; string::iterator i = this->begin()+_i;
this->insert( i, _val ); this->insert( i, _val );
} else } else
throw out_of_range( "out_of_range when inserting gene"); throw out_of_range( "out_of_range when inserting gene");
}; };
/** Eliminates the gene at position _i /** Eliminates the gene at position _i
@exception out_of_range if _i is larger than EO´s size @exception out_of_range if _i is larger than EO´s size
*/ */
virtual void deleteGene( unsigned _i ) { virtual void deleteGene( unsigned _i ) {
if (_i < this->size() ) { if (_i < this->size() ) {
string::iterator i = this->begin()+_i; string::iterator i = this->begin()+_i;
this->erase( i ); this->erase( i );
} else } else
throw out_of_range( "out_of_range when deleting gene"); throw out_of_range( "out_of_range when deleting gene");
}; };
/// methods that implement the EO <em>protocol</em> /// methods that implement the EO <em>protocol</em>
virtual unsigned length() const { return this->size(); }; virtual unsigned length() const { return this->size(); };
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eo1d readFrom and printOn are directly inherited from eo1d
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoString";}; virtual string className() const {return "eoString";};
//@} //@}
}; };
#endif #endif

View file

@ -1,91 +1,92 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoTranspose.h // eoTranspose.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOTRANSPOSE_h #ifndef _EOTRANSPOSE_h
#define _EOTRANSPOSE_h #define _EOTRANSPOSE_h
#include <eoUniform.h> #include <eoUniform.h>
#include <eoOp.h> #include <eoOp.h>
/** Transposition operator: interchanges the position of two genes /** Transposition operator: interchanges the position of two genes
of an EO. These positions must be defined by an only index, that is, of an EO. These positions must be defined by an only index, that is,
EOT must subclass eo1d EOT must subclass eo1d
*/ */
template <class EOT > template <class EOT >
class eoTranspose: public eoMonOp<EOT> { class eoTranspose: public eoMonOp<EOT> {
public: public:
/// ///
eoTranspose() eoTranspose()
: eoMonOp< EOT >( ){}; : eoMonOp< EOT >( ){};
/// needed virtual dtor /// needed virtual dtor
virtual ~eoTranspose() {}; virtual ~eoTranspose() {};
/// ///
virtual void operator()( EOT& _eo ) const { virtual void operator()( EOT& _eo ) const {
eoUniform<unsigned> uniform(0, _eo.length() ); eoUniform<unsigned> uniform(0, _eo.length() );
unsigned pos1 = uniform(), unsigned pos1 = uniform(),
pos2 = uniform(); pos2 = uniform();
applyAt( _eo, pos1, pos2 ); applyAt( _eo, pos1, pos2 );
} }
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp readFrom and printOn are directly inherited from eoOp
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoTranspose";}; virtual string className() const {return "eoTranspose";};
//@} //@}
private: private:
#ifdef _MSC_VER #ifdef _MSC_VER
typedef EOT::Type Type; typedef EOT::Type Type;
#else #else
typedef typename EOT::Type Type; typedef typename EOT::Type Type;
#endif #endif
/** applies operator to one gene in the EO /** applies operator to one gene in the EO
@param _eo victim of transposition @param _eo victim of transposition
@param i, j positions of the genes that are going to be changed @param i, j positions of the genes that are going to be changed
@throw runtime_exception if the positions to write are incorrect @throw runtime_exception if the positions to write are incorrect
*/ */
virtual void applyAt( EOT& _eo, unsigned _i, unsigned _j) const { virtual void applyAt( EOT& _eo, unsigned _i, unsigned _j) const {
try { try {
Type tmp = _eo.gene( _i ); Type tmp = _eo.gene( _i );
_eo.gene( _i ) = _eo.gene( _j ); _eo.gene( _i ) = _eo.gene( _j );
_eo.gene( _j ) = tmp; _eo.gene( _j ) = tmp;
} catch ( exception& _e ) { } catch ( exception& _e ) {
string msg = _e.what(); string msg = _e.what();
msg += "Caught exception at eoTranspose"; msg += "Caught exception at eoTranspose";
throw runtime_error( msg.c_str() ); throw runtime_error( msg.c_str() );
} }
} }
}; };
#endif #endif

View file

@ -1,64 +1,65 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoUniformSelect.h // eoUniformSelect.h
// (c) GeNeura Team, 1998 - EEAAX 1999 // (c) GeNeura Team, 1998 - EEAAX 1999
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoUniformSelect_h #ifndef eoUniformSelect_h
#define eoUniformSelect_h #define eoUniformSelect_h
// WARNING: 2 classes in this one - eoUniformSelect and eoCopySelect // WARNING: 2 classes in this one - eoUniformSelect and eoCopySelect
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <functional> // #include <functional> //
#include <numeric> // accumulate #include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT #include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h> #include <eoRNG.h>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** eoUniformSelect: a selection method that selects ONE individual randomly /** eoUniformSelect: a selection method that selects ONE individual randomly
-MS- 22/10/99 */ -MS- 22/10/99 */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
template <class EOT> class eoUniformSelect: public eoSelectOne<EOT> template <class EOT> class eoUniformSelect: public eoSelectOne<EOT>
{ {
public: public:
/// (Default) Constructor. /// (Default) Constructor.
eoUniformSelect():eoSelectOne<EOT>() {} eoUniformSelect():eoSelectOne<EOT>() {}
/// not a big deal!!! /// not a big deal!!!
virtual const EOT& operator()(const eoPop<EOT>& pop) { virtual const EOT& operator()(const eoPop<EOT>& pop) {
return pop[rng.random(pop.size())] ; return pop[rng.random(pop.size())] ;
} }
/// Methods inherited from eoObject /// Methods inherited from eoObject
//@{ //@{
/** Return the class id. /** Return the class id.
* @return the class name as a string * @return the class name as a string
*/ */
virtual string className() const { return "eoUniformSelect"; }; virtual string className() const { return "eoUniformSelect"; };
private: private:
}; };
#endif eoUniformSelect_h #endif eoUniformSelect_h

View file

@ -1,220 +1,221 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoWrappedOps.h eoWrappedOps.h
Derived from the General genetic operator, which can be used to wrap any unary or binary 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 operator. File also contains the eoCombinedOp, needed by the eoSequentialGOpSelector
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoWrappedOps_h #ifndef eoWrappedOps_h
#define eoWrappedOps_h #define eoWrappedOps_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp #include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include "eoRNG.h" #include "eoRNG.h"
using namespace std; using namespace std;
/// Wraps monary operators /// Wraps monary operators
template <class EOT> template <class EOT>
class eoWrappedMonOp : public eoGeneralOp<EOT> class eoWrappedMonOp : public eoGeneralOp<EOT>
{ {
public : public :
/// ///
eoWrappedMonOp(const eoMonOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}; eoWrappedMonOp(const eoMonOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {};
/// ///
virtual ~eoWrappedMonOp() {} virtual ~eoWrappedMonOp() {}
/// Instantiates the abstract method /// Instantiates the abstract method
void operator()( eoIndiSelector<EOT>& _in, void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const { eoInserter<EOT>& _out) const {
EOT result = _in.select(); EOT result = _in.select();
op( result ); op( result );
_out.insert(result); _out.insert(result);
} }
/// ///
virtual string className() const {return "eoWrappedMonOp";}; virtual string className() const {return "eoWrappedMonOp";};
private : private :
const eoMonOp<EOT>& op; const eoMonOp<EOT>& op;
}; };
/// Wraps binary operators /// Wraps binary operators
template <class EOT> template <class EOT>
class eoWrappedBinOp : public eoGeneralOp<EOT> class eoWrappedBinOp : public eoGeneralOp<EOT>
{ {
public : public :
/// ///
eoWrappedBinOp(const eoBinOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {} eoWrappedBinOp(const eoBinOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
/// ///
virtual ~eoWrappedBinOp() {} virtual ~eoWrappedBinOp() {}
/// Instantiates the abstract method. EOT should have copy ctor. /// Instantiates the abstract method. EOT should have copy ctor.
void operator()(eoIndiSelector<EOT>& _in, void operator()(eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const { eoInserter<EOT>& _out) const {
EOT out1 = _in.select(); EOT out1 = _in.select();
const EOT& out2 = _in.select(); const EOT& out2 = _in.select();
op(out1, out2); op(out1, out2);
_out.insert(out1); _out.insert(out1);
} }
/// ///
virtual string className() const {return "eoWrappedBinOp";}; virtual string className() const {return "eoWrappedBinOp";};
private : private :
const eoBinOp<EOT>& op; const eoBinOp<EOT>& op;
}; };
/// Wraps Quadratic operators /// Wraps Quadratic operators
template <class EOT> template <class EOT>
class eoWrappedQuadraticOp : public eoGeneralOp<EOT> class eoWrappedQuadraticOp : public eoGeneralOp<EOT>
{ {
public : public :
/// ///
eoWrappedQuadraticOp(const eoQuadraticOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {} eoWrappedQuadraticOp(const eoQuadraticOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
/// ///
virtual ~eoWrappedQuadraticOp() {} virtual ~eoWrappedQuadraticOp() {}
/// Instantiates the abstract method. EOT should have copy ctor. /// Instantiates the abstract method. EOT should have copy ctor.
void operator()(eoIndiSelector<EOT>& _in, void operator()(eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const { eoInserter<EOT>& _out) const {
EOT out1 = _in.select(); EOT out1 = _in.select();
EOT out2 = _in.select(); EOT out2 = _in.select();
op(out1, out2); op(out1, out2);
_out.insert(out1); _out.insert(out1);
_out.insert(out2); _out.insert(out2);
} }
/// ///
virtual string className() const {return "eoWrappedQuadraticOp";}; virtual string className() const {return "eoWrappedQuadraticOp";};
private : private :
const eoQuadraticOp<EOT>& op; const eoQuadraticOp<EOT>& op;
}; };
/// Combines several ops /// Combines several ops
template <class EOT> template <class EOT>
class eoCombinedOp : public eoGeneralOp<EOT> class eoCombinedOp : public eoGeneralOp<EOT>
{ {
public : public :
/// ///
eoCombinedOp() : eoGeneralOp<EOT>() {} eoCombinedOp() : eoGeneralOp<EOT>() {}
/// ///
virtual ~eoCombinedOp() {} virtual ~eoCombinedOp() {}
/// Adds a new operator to the combined Op /// Adds a new operator to the combined Op
void addOp(eoGeneralOp<EOT>* _op) void addOp(eoGeneralOp<EOT>* _op)
{ {
ops.push_back(_op); ops.push_back(_op);
} }
/// Erases all operators added so far /// Erases all operators added so far
void clear(void) { void clear(void) {
ops.resize(0); ops.resize(0);
} }
/// Helper class to make sure that stuff that is inserted will be used again with the next operator /// 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> class eoIndiSelectorInserter : public eoIndiSelector<EOT>, public eoInserter<EOT>
{ {
public : public :
eoIndiSelectorInserter(eoIndiSelector<EOT>& _in) eoIndiSelectorInserter(eoIndiSelector<EOT>& _in)
: eoIndiSelector<EOT>(), eoInserter<EOT>(), in(_in) : eoIndiSelector<EOT>(), eoInserter<EOT>(), in(_in)
{} {}
size_t size() const { return in.size(); } size_t size() const { return in.size(); }
const EOT& operator[](size_t _n) const { return in[_n]; } const EOT& operator[](size_t _n) const { return in[_n]; }
const EOT& select(void) const EOT& select(void)
{ {
if (results.empty()) if (results.empty())
{ {
return in.select(); return in.select();
} }
// else we use the previously inserted individual, // else we use the previously inserted individual,
// an iterator to it is stored in 'results', but the memory // an iterator to it is stored in 'results', but the memory
// is kept by 'intermediate'. // is kept by 'intermediate'.
list<EOT>::iterator it = *results.begin(); list<EOT>::iterator it = *results.begin();
results.pop_front(); results.pop_front();
return *it; return *it;
} }
void insert(const EOT& _eot) void insert(const EOT& _eot)
{ {
intermediate.push_front(_eot); intermediate.push_front(_eot);
results.push_front(intermediate.begin()); results.push_front(intermediate.begin());
} }
void fill(eoInserter<EOT>& _out) void fill(eoInserter<EOT>& _out)
{ {
typedef list<list<EOT>::iterator>::iterator Iterator; typedef list<list<EOT>::iterator>::iterator Iterator;
for (Iterator it = results.begin(); it != results.end(); ++it) for (Iterator it = results.begin(); it != results.end(); ++it)
{ {
_out.insert(**it); _out.insert(**it);
} }
results.clear(); results.clear();
intermediate.clear(); // reclaim memory intermediate.clear(); // reclaim memory
} }
private : private :
eoIndiSelector<EOT>& in; eoIndiSelector<EOT>& in;
// using lists as we need to push and pop a lot // using lists as we need to push and pop a lot
// 'results' are iterators to the contents of 'intermediate' // 'results' are iterators to the contents of 'intermediate'
// to prevent copying to and from intermediate... // to prevent copying to and from intermediate...
list<list<EOT>::iterator> results; list<list<EOT>::iterator> results;
list<EOT> intermediate; list<EOT> intermediate;
}; };
/// Applies all ops in the combined op /// Applies all ops in the combined op
void operator()( eoIndiSelector<EOT>& _in, void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out ) const { eoInserter<EOT>& _out ) const {
eoIndiSelectorInserter in_out(_in); eoIndiSelectorInserter in_out(_in);
for (size_t i = 0; i < ops.size(); ++i) for (size_t i = 0; i < ops.size(); ++i)
{ {
(*ops[i])(in_out, in_out); (*ops[i])(in_out, in_out);
} }
in_out.fill(_out); in_out.fill(_out);
} }
private : private :
vector<eoGeneralOp<EOT>* > ops; vector<eoGeneralOp<EOT>* > ops;
}; };
#endif eoGeneral_h #endif eoGeneral_h

View file

@ -1,106 +1,107 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoXOver2.h // eoXOver2.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOXOVER2_h #ifndef _EOXOVER2_h
#define _EOXOVER2_h #define _EOXOVER2_h
// for swap // for swap
#if defined( __BORLANDC__ ) #if defined( __BORLANDC__ )
#include <algorith> #include <algorith>
#else #else
#include <algorithm> #include <algorithm>
#endif #endif
// EO includes // EO includes
#include <eoOp.h> #include <eoOp.h>
#include <eoUniform.h> #include <eoUniform.h>
/** 2-point crossover: takes the genes in the central section of two EOs /** 2-point crossover: takes the genes in the central section of two EOs
and interchanges it and interchanges it
*/ */
template <class EOT> template <class EOT>
class eoXOver2: public eoQuadraticOp<EOT> { class eoXOver2: public eoQuadraticOp<EOT> {
public: public:
/// ///
eoXOver2() eoXOver2()
: eoQuadraticOp< EOT >(){}; : eoQuadraticOp< EOT >(){};
/// ///
virtual ~eoXOver2() {}; virtual ~eoXOver2() {};
/// ///
virtual void operator()( EOT& _eo1, virtual void operator()( EOT& _eo1,
EOT& _eo2 ) const { EOT& _eo2 ) const {
unsigned len1 = _eo1.length(), len2 = _eo2.length(), unsigned len1 = _eo1.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1; len= (len1 > len2)?len2:len1;
eoUniform<unsigned> uniform( 0, len ); eoUniform<unsigned> uniform( 0, len );
unsigned pos1 = uniform(), pos2 = uniform() ; unsigned pos1 = uniform(), pos2 = uniform() ;
applyAt( _eo1, _eo2, pos1, pos2 ); applyAt( _eo1, _eo2, pos1, pos2 );
} }
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp readFrom and printOn are directly inherited from eoOp
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
string className() const {return "eoXOver2";}; string className() const {return "eoXOver2";};
//@} //@}
private: private:
#ifdef _MSC_VER #ifdef _MSC_VER
typedef EOT::Type Type; typedef EOT::Type Type;
#else #else
typedef typename EOT::Type Type; typedef typename EOT::Type Type;
#endif #endif
/// applies operator to one gene in the EO /// applies operator to one gene in the EO
virtual void applyAt( EOT& _eo, EOT& _eo2, virtual void applyAt( EOT& _eo, EOT& _eo2,
unsigned _i, unsigned _j = 0) const { unsigned _i, unsigned _j = 0) const {
if ( _j < _i ) if ( _j < _i )
swap( _i, _j ); swap( _i, _j );
unsigned len1 = _eo.length(), len2 = _eo2.length(), unsigned len1 = _eo.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1; len= (len1 > len2)?len2:len1;
if ( (_j > len) || (_i> len ) ) if ( (_j > len) || (_i> len ) )
throw runtime_error( "xOver2: applying xOver past boundaries"); throw runtime_error( "xOver2: applying xOver past boundaries");
for ( unsigned i = _i; i < _j; i++ ) { for ( unsigned i = _i; i < _j; i++ ) {
Type tmp = _eo.gene( i ); Type tmp = _eo.gene( i );
_eo.gene( i ) = _eo2.gene( i ); _eo.gene( i ) = _eo2.gene( i );
_eo2.gene( i ) = tmp ; _eo2.gene( i ) = tmp ;
} }
} }
}; };
#endif #endif

View file

@ -1,85 +1,85 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
rnd_generators.h rnd_generators.h
Some utility functors for generating random generators: Some utility functors for generating random generators:
uniform_generator : generates uniform floats or doubles uniform_generator : generates uniform floats or doubles
random_generator : generates unsigneds, ints etc. random_generator : generates unsigneds, ints etc.
normal_generator : normally distributed floats or doubles normal_generator : normally distributed floats or doubles
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoRND_GENERATORS_H #ifndef eoRND_GENERATORS_H
#define eoRND_GENERATORS_H #define eoRND_GENERATORS_H
#include "eoRNG.h" #include "eoRNG.h"
/** /**
The class uniform_generator can be used in the STL generate function The class uniform_generator can be used in the STL generate function
to easily generate random floats and doubles between [0, _max). _max to easily generate random floats and doubles between [0, _max). _max
defaults to 1.0 defaults to 1.0
*/ */
template <class T = double> class uniform_generator template <class T = double> class uniform_generator
{ {
public : public :
uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {} uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {}
virtual T operator()(void) { return (T) uniform.uniform(maxim); } virtual T operator()(void) { return (T) uniform.uniform(maxim); }
private : private :
T maxim; T maxim;
eoRng& uniform; eoRng& uniform;
}; };
/** /**
The class random_generator can be used in the STL generate function The class random_generator can be used in the STL generate function
to easily generate random ints between [0, _max). to easily generate random ints between [0, _max).
*/ */
template <class T = uint32> class random_generator template <class T = uint32> class random_generator
{ {
public : public :
random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {} random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {}
virtual T operator()(void) { return (T) random.random(max); } virtual T operator()(void) { return (T) random.random(max); }
private : private :
T maxim; T maxim;
eoRng& random; eoRng& random;
}; };
/** /**
The class normal_generator can be used in the STL generate function The class normal_generator can be used in the STL generate function
to easily generate gaussian distributed floats and doubles. The user to easily generate gaussian distributed floats and doubles. The user
can supply a standard deviation which defaults to 1. can supply a standard deviation which defaults to 1.
*/ */
template <class T = double> class normal_generator template <class T = double> class normal_generator
{ {
public : public :
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
virtual T operator()(void) { return (T) normal.normal(stdev); } virtual T operator()(void) { return (T) normal.normal(stdev); }
private : private :
T stdev; T stdev;
eoRng& normal; eoRng& normal;
}; };
#endif #endif

View file

@ -1,313 +1,313 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
selectors.h selectors.h
A bunch of useful selector functions. They generally have three forms: A bunch of useful selector functions. They generally have three forms:
template <class It> template <class It>
It select(It begin, It end, params, eoRng& gen = rng); It select(It begin, It end, params, eoRng& gen = rng);
template <class EOT> template <class EOT>
const EOT& select(const eoPop<EOT>& pop, params, eoRng& gen = rng); const EOT& select(const eoPop<EOT>& pop, params, eoRng& gen = rng);
template <class EOT> template <class EOT>
EOT& select(eoPop<EOT>& pop, params, eoRng& gen = rng); EOT& select(eoPop<EOT>& pop, params, eoRng& gen = rng);
where select is one of: roulette_wheel, deterministic_tournament where select is one of: roulette_wheel, deterministic_tournament
and stochastic_tournament (at the moment). and stochastic_tournament (at the moment).
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef SELECT__H #ifndef SELECT__H
#define SELECT__H #define SELECT__H
#include "eoRNG.h" #include "eoRNG.h"
#include "eoException.h" #include "eoException.h"
template <class EOT> template <class EOT>
bool minimizing_fitness() bool minimizing_fitness()
{ {
EOT eo1; // Assuming people don't do anything fancy in the default constructor! EOT eo1; // Assuming people don't do anything fancy in the default constructor!
EOT eo2; EOT eo2;
/* Dear user, when the two line below do not compile you are most /* 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 likely not working with scalar fitness values. In that case we're sorry
but you cannot use lottery or roulette_wheel selection... 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 eo1.fitness(0.0); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this
eo2.fitness(1.0); eo2.fitness(1.0);
return eo2 < eo1; // check whether we have a minimizing fitness return eo2 < eo1; // check whether we have a minimizing fitness
}; };
inline double scale_fitness(const std::pair<double, double>& _minmax, double _value) inline double scale_fitness(const std::pair<double, double>& _minmax, double _value)
{ {
if (_minmax.first == _minmax.second) if (_minmax.first == _minmax.second)
{ {
return 0.0; // no differences in fitness, population converged! return 0.0; // no differences in fitness, population converged!
} }
// else // else
return (_value - _minmax.first) / (_minmax.second - _minmax.first); return (_value - _minmax.first) / (_minmax.second - _minmax.first);
} }
template <class It> template <class It>
double sum_fitness(It begin, It end) double sum_fitness(It begin, It end)
{ {
double sum = 0.0; double sum = 0.0;
for (; begin != end; ++begin) for (; begin != end; ++begin)
{ {
double v = static_cast<double>(begin->fitness()); double v = static_cast<double>(begin->fitness());
if (v < 0.0) if (v < 0.0)
throw eoNegativeFitnessException(); throw eoNegativeFitnessException();
sum += v; sum += v;
} }
return sum; return sum;
} }
template <class EOT> template <class EOT>
double sum_fitness(const eoPop<EOT>& _pop) double sum_fitness(const eoPop<EOT>& _pop)
{ {
return sum_fitness(_pop.begin(), _pop.end()); return sum_fitness(_pop.begin(), _pop.end());
} }
template <class EOT> template <class EOT>
double sum_fitness(const eoPop<EOT>& _pop, std::pair<double, double>& _minmax) double sum_fitness(const eoPop<EOT>& _pop, std::pair<double, double>& _minmax)
{ {
eoPop<EOT>::const_iterator it = _pop.begin(); eoPop<EOT>::const_iterator it = _pop.begin();
_minmax.first = it->fitness(); _minmax.first = it->fitness();
_minmax.second = it++->fitness(); _minmax.second = it++->fitness();
for(; it != _pop.end(); ++it) for(; it != _pop.end(); ++it)
{ {
double v = static_cast<double>(it->fitness()); double v = static_cast<double>(it->fitness());
_minmax.first = std::min(_minmax.first, v); _minmax.first = std::min(_minmax.first, v);
_minmax.second = std::max(_minmax.second, v); _minmax.second = std::max(_minmax.second, v);
rawTotal += v; rawTotal += v;
} }
if (minimizing_fitness<EOT>()) if (minimizing_fitness<EOT>())
{ {
std::swap(_minmax.first, _minmax.second); std::swap(_minmax.first, _minmax.second);
} }
scaledTotal = 0.0; scaledTotal = 0.0;
// unfortunately a second loop is neccessary to scale the fitness // unfortunately a second loop is neccessary to scale the fitness
for (it = _pop.begin(); it != _pop.end(); ++it) for (it = _pop.begin(); it != _pop.end(); ++it)
{ {
double v = scale_fitness(static_cast<double>(it->fitness())); double v = scale_fitness(static_cast<double>(it->fitness()));
scaledTotal += v; scaledTotal += v;
} }
} }
template <class It> template <class It>
It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng) It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng)
{ {
float roulette = _gen.uniform(total); float roulette = _gen.uniform(total);
It i = _begin; It i = _begin;
while (roulette > 0.0) while (roulette > 0.0)
{ {
roulette -= static_cast<double>(*(i++)); roulette -= static_cast<double>(*(i++));
} }
return --i; return --i;
} }
template <class EOT> template <class EOT>
const EOT& roulette_wheel(const eoPop<EOT>& _pop, double total, eoRng& _gen = rng) const EOT& roulette_wheel(const eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
{ {
float roulette = _gen.uniform(total); float roulette = _gen.uniform(total);
eoPop<EOT>::const_iterator i = _pop.begin(); eoPop<EOT>::const_iterator i = _pop.begin();
while (roulette > 0.0) while (roulette > 0.0)
{ {
roulette -= static_cast<double>((i++)->fitness()); roulette -= static_cast<double>((i++)->fitness());
} }
return *--i; return *--i;
} }
template <class EOT> template <class EOT>
EOT& roulette_wheel(eoPop<EOT>& _pop, double total, eoRng& _gen = rng) EOT& roulette_wheel(eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
{ {
float roulette = _gen.uniform(total); float roulette = _gen.uniform(total);
eoPop<EOT>::iterator i = _pop.begin(); eoPop<EOT>::iterator i = _pop.begin();
while (roulette > 0.0) while (roulette > 0.0)
{ {
roulette -= static_cast<double>((i++)->fitness()); roulette -= static_cast<double>((i++)->fitness());
} }
return *--i; return *--i;
} }
template <class It> template <class It>
It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
{ {
It best = _begin + _gen.random(_end - _begin); It best = _begin + _gen.random(_end - _begin);
for (unsigned i = 0; i < _t_size - 1; ++i) for (unsigned i = 0; i < _t_size - 1; ++i)
{ {
It competitor = _begin + _gen.random(_end - _begin); It competitor = _begin + _gen.random(_end - _begin);
if (*best < *competitor) if (*best < *competitor)
{ {
best = competitor; best = competitor;
} }
} }
return best; return best;
} }
template <class EOT> template <class EOT>
const EOT& deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng) const EOT& deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{ {
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
} }
template <class EOT> template <class EOT>
EOT& deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng) EOT& deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{ {
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
} }
template <class It> template <class It>
It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
{ {
It worst = _begin + _gen.random(_end - _begin); It worst = _begin + _gen.random(_end - _begin);
for (unsigned i = 0; i < _t_size - 1; ++i) for (unsigned i = 0; i < _t_size - 1; ++i)
{ {
It competitor = _begin + _gen.random(_end - _begin); It competitor = _begin + _gen.random(_end - _begin);
if (competitor == worst) if (competitor == worst)
{ {
--i; --i;
continue; // try again continue; // try again
} }
if (*competitor < *worst) if (*competitor < *worst)
{ {
worst = competitor; worst = competitor;
} }
} }
return worst; return worst;
} }
template <class EOT> template <class EOT>
const EOT& inverse_deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng) 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); return *inverse_deterministic_tournament<EOT>(_pop.begin(), _pop.end(), _t_size, _gen);
} }
template <class EOT> template <class EOT>
EOT& inverse_deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng) EOT& inverse_deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{ {
return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
} }
template <class It> template <class It>
It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
{ {
It i1 = _begin + _gen.random(_end - _begin); It i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin); It i2 = _begin + _gen.random(_end - _begin);
bool return_better = _gen.flip(_t_rate); bool return_better = _gen.flip(_t_rate);
if (*i1 < *i2) if (*i1 < *i2)
{ {
if (return_better) return i2; if (return_better) return i2;
// else // else
return i1; return i1;
} }
else else
{ {
if (return_better) return i1; if (return_better) return i1;
// else // else
} }
// else // else
return i2; return i2;
} }
template <class EOT> template <class EOT>
const EOT& stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng) const EOT& stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{ {
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
} }
template <class EOT> template <class EOT>
EOT& stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng) EOT& stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{ {
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
} }
template <class It> template <class It>
It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
{ {
It i1 = _begin + _gen.random(_end - _begin); It i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin); It i2 = _begin + _gen.random(_end - _begin);
bool return_worse = _gen.flip(_t_rate); bool return_worse = _gen.flip(_t_rate);
if (*i1 < *i2) if (*i1 < *i2)
{ {
if (return_worse) return i1; if (return_worse) return i1;
// else // else
return i2; return i2;
} }
else else
{ {
if (return_worse) return i2; if (return_worse) return i2;
// else // else
} }
// else // else
return i1; return i1;
} }
template <class EOT> template <class EOT>
const EOT& inverse_stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng) 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); return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
} }
template <class EOT> template <class EOT>
EOT& inverse_stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng) EOT& inverse_stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{ {
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
} }
#endif #endif