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

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

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

@ -1,76 +1,76 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
compatibility.h
File to store some compiler specific stuff in. Currently handles, or
least tries to handle the min() max() problems when using MSVC
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
#ifndef COMPAT_H
#define COMPAT_H
#include <string>
#include <iostream>
#ifdef _1__GNUC__
// Specifics for GNUC
#define NO_GOOD_ISTREAM_ITERATORS
#endif
#ifdef _MSC_VER
/*
Maarten: added this code here because Mirkosoft has the
nasty habit of #define min and max in stdlib.h (and windows.h)
I'm trying to undo this horrible macro magic (microsoft yet macrohard)
here. Sure hope it works
*/
#include <stdlib.h>
#ifdef min
#undef min
#undef max // as they come in pairs
#endif
// add min and max to std...
namespace std
{
template <class T> T min(const T& a, const T& b)
{
if(a < b)
return a;
// else
return b;
}
template <class T> T max(const T& a, const T& b)
{
if(a > b)
return a;
// else
return b;
}
}
#endif // _MSC_VER
#endif
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
-----------------------------------------------------------------------------
compatibility.h
File to store some compiler specific stuff in. Currently handles, or
least tries to handle the min() max() problems when using MSVC
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
#ifndef COMPAT_H
#define COMPAT_H
#include <string>
#include <iostream>
#ifdef _1__GNUC__
// Specifics for GNUC
#define NO_GOOD_ISTREAM_ITERATORS
#endif
#ifdef _MSC_VER
/*
Maarten: added this code here because Mirkosoft has the
nasty habit of #define min and max in stdlib.h (and windows.h)
I'm trying to undo this horrible macro magic (microsoft yet macrohard)
here. Sure hope it works
*/
#include <stdlib.h>
#ifdef min
#undef min
#undef max // as they come in pairs
#endif
// add min and max to std...
namespace std
{
template <class T> T min(const T& a, const T& b)
{
if(a < b)
return a;
// else
return b;
}
template <class T> T max(const T& a, const T& b)
{
if(a > b)
return a;
// else
return b;
}
}
#endif // _MSC_VER
#endif

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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