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

Some files were not shown because too many files have changed in this diff Show more