From 0d439f9f56aab9c704defb416de524354b750e1a Mon Sep 17 00:00:00 2001 From: mac Date: Sat, 19 Feb 2000 18:21:47 +0000 Subject: [PATCH] Changed double linefeeds, will undo this if it doesn't work --- eo/gp/eoParseTree.h | 476 +++---- eo/gp/node_pool.h | 456 +++---- eo/gp/parse_tree.h | 1830 +++++++++++++------------- eo/src/compatibility.h | 152 +-- eo/src/eoAged.h | 217 +-- eo/src/eoAtomCreep.h | 131 +- eo/src/eoAtomMutation.h | 191 +-- eo/src/eoAtomMutator.h | 123 +- eo/src/eoBackInserter.h | 108 +- eo/src/eoBitOp.h | 649 ++++----- eo/src/eoBitOpFactory.h | 239 ++-- eo/src/eoBreeder.h | 227 ++-- eo/src/eoData.h | 115 +- eo/src/eoDetTournament.h | 141 +- eo/src/eoDetTournamentIndiSelector.h | 114 +- eo/src/eoDetTournamentInserter.h | 138 +- eo/src/eoDup.h | 127 +- eo/src/eoESChrom.h | 251 ++-- eo/src/eoESFullChrom.h | 537 ++++---- eo/src/eoEasyEA.h | 165 +-- eo/src/eoEvalFuncPtr.h | 119 +- eo/src/eoException.h | 138 +- eo/src/eoFitTerm.h | 129 +- eo/src/eoFitness.h | 109 +- eo/src/eoGOpBreeder.h | 117 +- eo/src/eoGOpSelector.h | 347 ++--- eo/src/eoGenTerm.h | 165 +-- eo/src/eoID.h | 219 +-- eo/src/eoIndiSelector.h | 268 ++-- eo/src/eoInserter.h | 185 +-- eo/src/eoKill.h | 123 +- eo/src/eoLottery.h | 195 +-- eo/src/eoMultiBinOp.h | 199 +-- eo/src/eoMultiMonOp.h | 160 +-- eo/src/eoMutation.h | 181 +-- eo/src/eoNegExp.h | 133 +- eo/src/eoNonUniform.h | 173 +-- eo/src/eoNormal.h | 177 +-- eo/src/eoObject.h | 137 +- eo/src/eoOp.h | 471 +++---- eo/src/eoPersistent.cpp | 29 +- eo/src/eoPersistent.h | 144 +- eo/src/eoPop.h | 321 ++--- eo/src/eoPrintable.h | 125 +- eo/src/eoProblem.h | 85 +- eo/src/eoProportionalGOpSelector.h | 109 +- eo/src/eoProportionalOpSel.h | 313 ++--- eo/src/eoRNG.h | 905 ++++++------- eo/src/eoRandomIndiSelector.h | 103 +- eo/src/eoSequentialGOpSelector.h | 123 +- eo/src/eoSteadyStateEA.h | 173 +-- eo/src/eoSteadyStateGeneration.h | 177 +-- eo/src/eoSteadyStateInserter.h | 102 +- eo/src/eoStochTournament.h | 137 +- eo/src/eoStochTournamentInserter.h | 146 +- eo/src/eoString.h | 281 ++-- eo/src/eoTranspose.h | 183 +-- eo/src/eoUniformSelect.h | 129 +- eo/src/eoWrappedOps.h | 441 +++---- eo/src/eoXOver2.h | 213 +-- eo/src/rnd_generators.h | 170 +-- eo/src/selectors.h | 626 ++++----- 62 files changed, 7612 insertions(+), 7555 deletions(-) diff --git a/eo/gp/eoParseTree.h b/eo/gp/eoParseTree.h index a83b45fe..5aa4bcf4 100644 --- a/eo/gp/eoParseTree.h +++ b/eo/gp/eoParseTree.h @@ -1,238 +1,238 @@ -#ifndef EO_PARSE_TREE_H -#define EO_PARSE_TREE_H - -#include - -#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 eoParseTree : public EO, public parse_tree -{ -public : - - typedef typename parse_tree::subtree Type; - - eoParseTree(void) : EO(), parse_tree() {} - eoParseTree(unsigned _size, eoRnd& _rnd) - : EO(), parse_tree(_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(), parse_tree() - { - readFrom(is); - } - - string className(void) const { return "eoParseTree"; } - - void printOn(std::ostream& os) const - { - os << fitness() << ' '; - - std::copy(ebegin(), eend(), ostream_iterator(os)); - } - - void readFrom(std::istream& is) - { - FType fit; - - is >> fit; - - fitness(fit); - - std::copy(istream_iterator(is), istream_iterator(), back_inserter(*this)); - } -}; - -template -std::ostream& operator<<(std::ostream& os, const eoParseTree& eot) -{ - eot.printOn(os); - return os; -} - -template -std::istream& operator>>(std::istream& is, eoParseTree& eot) -{ - eot.readFrom(is); - return is; -} - - - -template -class eoGpDepthInitializer : public eoRnd< eoParseTree::Type > -{ - public : - - typedef eoParseTree EoType; - - eoGpDepthInitializer( - unsigned _max_depth, - const vector& _initializor, - bool _grow = true) - : - eoRnd(), - max_depth(_max_depth), - initializor(_initializor), - grow(_grow) - {} - - virtual string className() const { return "eoDepthInitializer"; }; - - EoType::Type operator()(void) - { - list sequence; - - generate(sequence, max_depth); - - parse_tree tree(sequence.begin(), sequence.end()); - - return tree.root(); - } - - void generate(list& sequence, int the_max, int last_terminal = -1) - { - if (last_terminal == -1) - { // check where the last terminal in the sequence resides - vector::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::iterator it = initializor.begin() + rng.random(last_terminal); - sequence.push_front(*it); - return; - } - - vector::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 initializor; - bool grow; -}; - -template -class eoSubtreeXOver: public eoGeneralOp< eoParseTree > { -public: - - typedef eoParseTree EoType; - - eoSubtreeXOver( unsigned _max_length) - : eoGeneralOp(), max_length(_max_length) {}; - - virtual string className() const { return "eoSubtreeXOver"; }; - - /// Dtor - virtual ~eoSubtreeXOver () {}; - - void operator()(eoIndiSelector& _source, eoInserter& _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 eoBranchMutation: public eoGeneralOp< eoParseTree > -{ -public: - - typedef eoParseTree EoType; - - eoBranchMutation(eoRnd& _init, unsigned _max_length) - : eoGeneralOp(), max_length(_max_length), initializer(_init) - {}; - - virtual string className() const { return "eoBranchMutation"; }; - - /// Dtor - virtual ~eoBranchMutation() {}; - - void operator()(eoIndiSelector& _source, eoInserter& _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& initializer; -}; - - -#endif \ No newline at end of file +#ifndef EO_PARSE_TREE_H +#define EO_PARSE_TREE_H + +#include + +#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 eoParseTree : public EO, public parse_tree +{ +public : + + typedef typename parse_tree::subtree Type; + + eoParseTree(void) : EO(), parse_tree() {} + eoParseTree(unsigned _size, eoRnd& _rnd) + : EO(), parse_tree(_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(), parse_tree() + { + readFrom(is); + } + + string className(void) const { return "eoParseTree"; } + + void printOn(std::ostream& os) const + { + os << fitness() << ' '; + + std::copy(ebegin(), eend(), ostream_iterator(os)); + } + + void readFrom(std::istream& is) + { + FType fit; + + is >> fit; + + fitness(fit); + + std::copy(istream_iterator(is), istream_iterator(), back_inserter(*this)); + } +}; + +template +std::ostream& operator<<(std::ostream& os, const eoParseTree& eot) +{ + eot.printOn(os); + return os; +} + +template +std::istream& operator>>(std::istream& is, eoParseTree& eot) +{ + eot.readFrom(is); + return is; +} + + + +template +class eoGpDepthInitializer : public eoRnd< eoParseTree::Type > +{ + public : + + typedef eoParseTree EoType; + + eoGpDepthInitializer( + unsigned _max_depth, + const vector& _initializor, + bool _grow = true) + : + eoRnd(), + max_depth(_max_depth), + initializor(_initializor), + grow(_grow) + {} + + virtual string className() const { return "eoDepthInitializer"; }; + + EoType::Type operator()(void) + { + list sequence; + + generate(sequence, max_depth); + + parse_tree tree(sequence.begin(), sequence.end()); + + return tree.root(); + } + + void generate(list& sequence, int the_max, int last_terminal = -1) + { + if (last_terminal == -1) + { // check where the last terminal in the sequence resides + vector::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::iterator it = initializor.begin() + rng.random(last_terminal); + sequence.push_front(*it); + return; + } + + vector::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 initializor; + bool grow; +}; + +template +class eoSubtreeXOver: public eoGeneralOp< eoParseTree > { +public: + + typedef eoParseTree EoType; + + eoSubtreeXOver( unsigned _max_length) + : eoGeneralOp(), max_length(_max_length) {}; + + virtual string className() const { return "eoSubtreeXOver"; }; + + /// Dtor + virtual ~eoSubtreeXOver () {}; + + void operator()(eoIndiSelector& _source, eoInserter& _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 eoBranchMutation: public eoGeneralOp< eoParseTree > +{ +public: + + typedef eoParseTree EoType; + + eoBranchMutation(eoRnd& _init, unsigned _max_length) + : eoGeneralOp(), max_length(_max_length), initializer(_init) + {}; + + virtual string className() const { return "eoBranchMutation"; }; + + /// Dtor + virtual ~eoBranchMutation() {}; + + void operator()(eoIndiSelector& _source, eoInserter& _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& initializer; +}; + + +#endif diff --git a/eo/gp/node_pool.h b/eo/gp/node_pool.h index d2f70fe9..35cc4ab2 100644 --- a/eo/gp/node_pool.h +++ b/eo/gp/node_pool.h @@ -1,228 +1,228 @@ - -#ifndef node_pool_h -#define node_pool_h - -class MemPool -{ -public : - - MemPool(unsigned int sz) : esize(sznext; - delete p; - } - } - - void* allocate() - { - if (head == 0) grow(); - Link* p = head; - head = p->next; - return static_cast(p); - } - - void deallocate(void* b) - { - Link* p = static_cast(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(p)->next = - reinterpret_cast(p + esize); - } - - reinterpret_cast(last)->next = 0; - head = reinterpret_cast(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 Node_alloc -{ -public : - Node_alloc() {}; - - T* allocate(void) - { - T* t = static_cast(mem.allocate()); - t = new (t) T; - //t->T(); // call constructor; - return t; - } - - void deallocate(T* t) - { - t->~T(); // call destructor - mem.deallocate(static_cast(t)); - } - -private : - static MemPool mem; -}; - -template -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 Standard_Node_alloc -{ -public : - Standard_Node_alloc() {} - - T* allocate(void) - { - return new T;// [arity]; - } - - void deallocate(T* t) - { - delete t; - } - -}; - -template -class Tree_alloc -{ -public : - Tree_alloc() {} - - T* allocate(size_t arity) - { - T* t; - - switch(arity) - { - - case 0 : return 0; - case 1 : - { - t = static_cast(mem1.allocate()); - new (t) T; - break; - } - case 2 : - { - t = static_cast(mem2.allocate()); - new (t) T; - new (&t[1]) T; - break; - } - case 3 : - { - t = static_cast(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(t)); - return; - } - case 2 : - { - t[1].~T(); t[0].~T(); - mem2.deallocate(static_cast(t)); - return; - } - case 1 : - { - t[0].~T(); - mem1.deallocate(static_cast(t)); - return; - } - default : - { - delete [] t; - return; - } - } - } - - -private : - static MemPool mem1; - static MemPool mem2; - static MemPool mem3; -}; - -// static (non thread_safe) memory pools -template MemPool Node_alloc::mem = sizeof(T); -template MemPool Tree_alloc::mem1 = sizeof(T); -template MemPool Tree_alloc::mem2 = sizeof(T) * 2; -template MemPool Tree_alloc::mem3 = sizeof(T) * 3; - -#endif \ No newline at end of file + +#ifndef node_pool_h +#define node_pool_h + +class MemPool +{ +public : + + MemPool(unsigned int sz) : esize(sznext; + delete p; + } + } + + void* allocate() + { + if (head == 0) grow(); + Link* p = head; + head = p->next; + return static_cast(p); + } + + void deallocate(void* b) + { + Link* p = static_cast(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(p)->next = + reinterpret_cast(p + esize); + } + + reinterpret_cast(last)->next = 0; + head = reinterpret_cast(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 Node_alloc +{ +public : + Node_alloc() {}; + + T* allocate(void) + { + T* t = static_cast(mem.allocate()); + t = new (t) T; + //t->T(); // call constructor; + return t; + } + + void deallocate(T* t) + { + t->~T(); // call destructor + mem.deallocate(static_cast(t)); + } + +private : + static MemPool mem; +}; + +template +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 Standard_Node_alloc +{ +public : + Standard_Node_alloc() {} + + T* allocate(void) + { + return new T;// [arity]; + } + + void deallocate(T* t) + { + delete t; + } + +}; + +template +class Tree_alloc +{ +public : + Tree_alloc() {} + + T* allocate(size_t arity) + { + T* t; + + switch(arity) + { + + case 0 : return 0; + case 1 : + { + t = static_cast(mem1.allocate()); + new (t) T; + break; + } + case 2 : + { + t = static_cast(mem2.allocate()); + new (t) T; + new (&t[1]) T; + break; + } + case 3 : + { + t = static_cast(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(t)); + return; + } + case 2 : + { + t[1].~T(); t[0].~T(); + mem2.deallocate(static_cast(t)); + return; + } + case 1 : + { + t[0].~T(); + mem1.deallocate(static_cast(t)); + return; + } + default : + { + delete [] t; + return; + } + } + } + + +private : + static MemPool mem1; + static MemPool mem2; + static MemPool mem3; +}; + +// static (non thread_safe) memory pools +template MemPool Node_alloc::mem = sizeof(T); +template MemPool Tree_alloc::mem1 = sizeof(T); +template MemPool Tree_alloc::mem2 = sizeof(T) * 2; +template MemPool Tree_alloc::mem3 = sizeof(T) * 3; + +#endif diff --git a/eo/gp/parse_tree.h b/eo/gp/parse_tree.h index 3d501b03..cb3b2ec2 100644 --- a/eo/gp/parse_tree.h +++ b/eo/gp/parse_tree.h @@ -1,915 +1,915 @@ -#ifndef PARSE_TREE_HH -#define PARSE_TREE_HH - -/** - - * Parse_tree and subtree classes - * (c) Maarten Keijzer 1999 - - * These classes may be used for educational and - * other non-commercial purposes only. Even if I - * wanted to, I am not at liberty to place this file - * under the GNU Lesser Public Library License, as this - * would limit my and my institution's freedom to use - * this file in closed-source software. - - * This material is provided "as is", with absolutely no warranty expressed - * or implied. Any use is at your own risk. - * - * Permission to use or copy this software for non-commercial purpose is hereby granted - * without fee, provided the above notices are retained on all copies. - * Permission to modify the code and to distribute modified code is granted, - * provided the above notices are retained, and a notice that the code was - * modified is included with the above copyright notice. - * - - - Usage information. - - class Node (your node in the tree) must have the following implemented: - - ****** Arity ****** - - int arity(void) const - - Note: the default constructor of a Node should provide a - Node with arity 0! - - ****** Evaluation ****** - - A parse_tree is evaluated through one of it's apply() members: - - 1) parse_tree::apply(void) - - is the simplest evaluation, it will call - - RetVal Node::operator()(subtree::const_iterator) - - 2) parse_tree::apply(It values) - - will call: - - RetVal Node::operator()(subtree<... , It values) - - where It is whatever type you desire (most of the time - this will be a vector containing the values of your - variables); - - 3) parse_tree::apply(It values, It2 moreValues) - - will call: - - RetVal Node::operator()(subtree<... , It values, It2 moreValues) - - although I do not see the immediate use of this, however... - - 4) parse_tree::apply(It values, It2 args, It3 adfs) - - that calls: - - RetVal Node::operator()(subtree<... , It values, It2 args, It3 adfs) - - can be useful for implementing adfs. - - - In general it is a good idea to leave the specifics of the - arguments open so that different ways of evaluation remain - possible. Implement the simplest eval as: - - template - RetVal operator()(It begin) const - - ****** Internal Structure ****** - - A parse_tree has two template arguments: the Node and the ReturnValue - produced by evaluating the node. The structure of the tree is defined - through a subtree class that has the same two template arguments. - - The nodes are stored in a tree like : - - node4 - / \ - node3 node2 - / \ - node1 node0 - - where nodes 2 and 4 have arity 2 and nodes 0,1 and 3 arity 0 (terminals) - - The nodes are subtrees, containing the structure of the tree, together - with its size and depth. They contain a Node, the user defined template - argument. To access these nodes from a subtree, use operator-> or operator*. - - The numbers behind the nodes define a reverse-polish or postfix - traversel through the tree. The parse_tree defines iterators - on the tree such that - - tree.begin() points at the subtree at node0 and - tree.back() returns the subtree at node4, the complete tree - - Likewise operator[] is defined on the tree, such that: - - tree[0] will return the subtree at node0, while - tree[2] will return the subtree at node2 - - Assigments of subtrees is protected so that the code: - - tree[2] = tree[0]; - - will not crash and result in a tree structured as: - - node4 - / \ - node3 node0 - - Note that the rank numbers no longer specify their place in the tree: - - tree[0] still points at node0, but - tree[1] now points to node3 and - tree[2] points at the root node4 - - Embedded iterators are implemented to iterate over nodes rather - than subtrees. So an easy way to copy your tree to a vector is: - - vector vec(tree.size()); - copy(tree.ebegin(), tree.eend(), vec.begin()); - - You can also copy it to an ostream_iterator with this - technique, given that your Node implements an appropriate - operator<<. Reinitializing a tree with the vector is also - simple: - - tree.clear(); - copy(vec.begin(), vec.end(), back_inserter(tree)); - - Note that the back_inserter must be used as there is no - resize member in the parse_tree. back_inserter will use - the push_back member from the parse_tree - -*/ - -#include -#include // for swap - -#ifdef _MSC_VER -#pragma warning(disable : 4786) // disable this nagging warning about the limitations of the mirkosoft debugger -#endif - -namespace gp_parse_tree -{ - -#include "node_pool.h" - - -template -inline void do_the_swap(T& a, T& b) -{ - T tmp = a; - a = b; - b = tmp; -} - -template class parse_tree -{ - public : - -class subtree -{ - -// a bit nasty way to use a pool allocator (which would otherwise use slooow new and delete) -#if (defined(__GNUC__) || defined(_MSC_VER)) && !defined(_MT) - Node_alloc node_allocator; - Tree_alloc tree_allocator; -#else - Standard_Node_alloc node_allocator; - Standard_alloc tree_allocator; -#endif - -public : - - typedef subtree* iterator; - typedef const subtree* const_iterator; - //typedef std::vector::const_reverse_iterator const_reverse_iterator; - - /* Constructors, assignments */ - - subtree(void) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - {} - subtree(const subtree& s) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - { copy(s); } - subtree(const T& t) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - { copy(t); } - - template - subtree(It b, It e) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - { // initialize in prefix way for efficiency reasons - init(b, --e); - } - - virtual ~subtree(void) { tree_allocator.deallocate(args, arity()); node_allocator.deallocate(content); } - - subtree& operator=(const subtree& s) - { - if (s.get_root() == get_root()) - { // from the same tree, maybe a child. Don't take any chances - subtree anotherS = s; - return copy(anotherS); - } - - return copy(s); - } - - subtree& operator=(const T& t) { return copy(t); } - - /* Access to the nodes */ - - T& operator*(void) { return *content; } - const T& operator*(void) const { return *content; } - T* operator->(void) { return content; } - const T* operator->(void) const { return content; } - - /* Equality, inequality check, Node needs to implement operator== */ - - bool operator==(const subtree& other) const - { - if (! (*content == *other.content)) - return false; - - for (int i = 0; i < arity(); i++) - { - if (!(args[i] == other.args[i])) - return false; - } - - return true; - } - - bool operator !=(const subtree& other) const - { - return !operator==(other); - } - - /* Arity */ - int arity(void) const { return content->arity(); } - - /* Evaluation with an increasing amount of user defined arguments */ - template - RetVal apply(RetVal v) const { return (*content)(v, begin()); } - - template - RetVal apply(RetVal v, It values) const { return (*content)(v, begin(), values); } - - template - RetVal apply(RetVal v, It values, It2 moreValues) const - { return (*content)(v, begin(), values, moreValues); } - - template - RetVal apply(RetVal v, It values, It2 moreValues, It3 evenMoreValues) const - { return (*content)(v, begin(), values, moreValues, evenMoreValues); } - - - /* Iterators */ - - iterator begin(void) { return args; } - const_iterator begin(void) const { return args; } - - iterator end(void) { return args + arity(); } - const_iterator end(void) const { return args + arity(); } - - subtree& operator[](int i) { return *(begin() + i); } - const subtree& operator[](int i) const { return *(begin() + i); } - - /* Some statistics */ - - size_t size(void) const { return _size; } - - size_t cumulative_size(void) const { return _cumulative_size; } - size_t depth(void) const { return _depth; } - - const subtree& select_cumulative(size_t which) const - { return imp_select_cumulative(which); } - - subtree& select_cumulative(size_t which) - { return const_cast(imp_select_cumulative(which)); } - - subtree& get_node(size_t which) - { return const_cast(imp_get_node(which));} - const subtree& get_node(size_t which) const - { return imp_get_node(which); } - - subtree* get_parent(void) { return parent; } - const subtree* get_parent(void) const { return parent; } - - void clear(void) - { tree_allocator.deallocate(args, arity()); args = 0; *content = T(); parent = 0; _cumulative_size = 0; _depth = 0; _size = 0; } - - void swap(subtree& y) - { - do_the_swap(content, y.content); - do_the_swap(args, y.args); - do_the_swap(parent, y.parent); - - do_the_swap(_cumulative_size, y._cumulative_size); - do_the_swap(_depth, y._depth); - do_the_swap(_size, y._size); - updateAfterInsert(); - } - - friend void swap(subtree& x, subtree& y) - { - x.swap(y); - } - -protected : - - virtual void updateAfterInsert(void) - { - _depth = 0; - _size = 1; - _cumulative_size = 0; - - for (iterator it = begin(); it != end(); ++it) - { - _size += it->size(); - _cumulative_size += it->_cumulative_size; - _depth = it->_depth > _depth? it->_depth: _depth; - } - _cumulative_size += _size; - _depth++; - - if (parent) - parent->updateAfterInsert(); - } - -private : - - const subtree& imp_select_cumulative(size_t which) const - { - if (which >= (_cumulative_size - size())) - return *this; - // else - - for (int i = arity() - 1; i >= 0; --i) - { - if (which < args[i]._cumulative_size) - return args[i].imp_select_cumulative(which); - which -= args[i]._cumulative_size; - } - - return *this; // error! - } - - const subtree& imp_get_node(size_t which) const - { - if (which == size() - 1) - return *this; - - for (int i = arity() - 1; i >= 0; --i) - { - unsigned c_size = args[i].size(); - if (which < c_size) - return args[i].imp_get_node(which); - which -= c_size; - } - - return *this; // error! - } - - const subtree* get_root(void) const - { - if (parent == 0) - return this; - // else - - return parent->get_root(); - } - - subtree& copy(const subtree& s) - { - int oldArity = arity(); - - disown(); - - int ar = s.arity(); - - if (ar != oldArity) - { - tree_allocator.deallocate(args, oldArity); - - args = tree_allocator.allocate(ar); - - //if (ar > 0) - // args = new subtree [ar]; - //else - // args = 0; - } - - switch(ar) - { - case 3 : args[2].copy(s.args[2]); // no break! - case 2 : args[1].copy(s.args[1]); - case 1 : args[0].copy(s.args[0]); break; - case 0 : break; - default : - { - for (int i = 0; i < ar; ++i) - { - args[i].copy(s.args[i]); - } - } - } - - *content = *s.content; - - adopt(); - updateAfterInsert(); - return *this; - } - - subtree& copy(const T& t) - { - int oldArity = arity(); - - if (content != &t) - *content = t; - else - oldArity = -1; - - int ar = arity(); - - if (ar != oldArity) - { - if (oldArity != -1) - tree_allocator.deallocate(args, oldArity); - - args = tree_allocator.allocate(ar); - - //if (ar > 0) - // args = new subtree [ar]; - //else - // args = 0; - } - - adopt(); - updateAfterInsert(); - return *this; - } - - void disown(void) - { - switch(arity()) - { - case 3 : args[2].parent = 0; // no break! - case 2 : args[1].parent = 0; - case 1 : args[0].parent = 0; break; - case 0 : break; - default : - { - for (iterator it = begin(); it != end(); ++it) - { - it->parent = 0; - } - } - } - - } - - void adopt(void) - { - switch(arity()) - { - case 3 : args[2].parent = this; // no break! - case 2 : args[1].parent = this; - case 1 : args[0].parent = this; break; - case 0 : break; - default : - { - for (iterator it = begin(); it != end(); ++it) - { - it->parent = this; - } - } - } - } - - template - void init(It b, It& last) - { - *this = *last; - -#ifndef NDEBUG - if (last == b && arity() > 0) - { - throw "subtree::init()"; - } -#endif - - for (int i = 0; i < arity(); ++i) - { - args[i].parent = 0; - args[i].init(b, --last); - args[i].parent = this; - } - - updateAfterInsert(); - } - - T* content; - subtree* args; - subtree* parent; - - size_t _cumulative_size; - size_t _depth; - size_t _size; -}; - -// Continuing with parse_tree - - typedef T value_type; - - /* Constructors and Assignments */ - - parse_tree(void) : _root(), pushed() {} - parse_tree(const parse_tree& org) : _root(org._root), pushed(org.pushed) { } - parse_tree(const subtree& sub) : _root(sub), pushed() { } - - template - parse_tree(It b, It e) : _root(b, e), pushed() {} - - virtual ~parse_tree(void) {} - - parse_tree& operator=(const parse_tree& org) { return copy(org); } - parse_tree& operator=(const subtree& sub) - { return copy(sub); } - - - /* Equality and inequality */ - - bool operator==(const parse_tree& other) const - { return _root == other._root; } - - bool operator !=(const parse_tree& other) const - { return !operator==(other); } - - /* Simple tree statistics */ - - size_t size(void) const { return _root.size(); } - size_t depth(void) const { return _root.depth(); } - void clear(void) { _root.clear(); pushed.resize(0); } - - /* Evaluation (application), with an increasing number of user defined arguments */ - - template - RetVal apply(RetVal v) const - { return _root.apply(v); } - - template - RetVal apply(RetVal v, It varValues) const - { return _root.apply(v, varValues); } - - template - RetVal apply(RetVal v, It varValues, It2 moreValues) const - { return _root.apply(v, varValues, moreValues); } - - template - RetVal apply(RetVal v, It varValues, It2 moreValues, It3 evenMoreValues) const - { return _root.apply(v, varValues, moreValues, evenMoreValues); } - - /* Customized Swap */ - void swap(parse_tree& other) - { - do_the_swap(pushed, other.pushed); - _root.swap(other._root); - } - - /* Definitions of the iterators */ - - class base_iterator - { - public : - - base_iterator() {} - base_iterator(subtree* n) { node = n; } - - base_iterator& operator=(const base_iterator& org) - { node = org.node; return *this; } - - bool operator==(const base_iterator& org) const - { return node == org.node; } - bool operator!=(const base_iterator& org) const - { return !operator==(org); } - - base_iterator operator+(size_t n) const - { - base_iterator tmp = *this; - - for(;n != 0; --n) - { - ++tmp; - } - - return tmp; - } - - base_iterator& operator++(void) - { - subtree* parent = node->get_parent(); - - if (parent == 0) - { - node = 0; - return *this; - } - // else - subtree::iterator it; - for (it = parent->begin(); it != parent->end(); ++it) - { - if (node == &(*it)) - break; - } - - if (it == parent->begin()) - node = parent; - else - { - node = &(--it)->get_node(0); - } - - return *this; - } - - base_iterator operator++(int) - { - base_iterator tmp = *this; - operator++(); - return tmp; - } - - protected : - subtree* node; - }; - - class iterator : public base_iterator - { - public : - typedef std::forward_iterator_tag iterator_category; - typedef subtree value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef subtree* pointer; - typedef subtree& reference; - - iterator() : base_iterator() {} - iterator(subtree* n): base_iterator(n) {} - iterator& operator=(const iterator& org) - { base_iterator::operator=(org); return *this; } - - subtree& operator*(void) { return *node; } - subtree* operator->(void) { return node; } - }; - - class embedded_iterator : public base_iterator - { - public : - typedef std::forward_iterator_tag iterator_category; - typedef T value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef T* pointer; - typedef T& reference; - - embedded_iterator() : base_iterator() {} - embedded_iterator(subtree* n): base_iterator(n) {} - embedded_iterator& operator=(const embedded_iterator& org) - { base_iterator::operator=(org); return *this; } - - T& operator*(void) { return **node; } - T* operator->(void) { return &**node; } - }; - - class base_const_iterator - { - public : - base_const_iterator() {} - base_const_iterator(const subtree* n) { node = n; } - - base_const_iterator& operator=(const base_const_iterator& org) - { node = org.node; return *this; } - - bool operator==(const base_const_iterator& org) const - { return node == org.node; } - bool operator!=(const base_const_iterator& org) const - { return !operator==(org); } - - base_const_iterator& operator++(void) - { - const subtree* parent = node->get_parent(); - - if (parent == 0) - { - node = 0; - return *this; - } - // else - subtree::const_iterator it; - - for (it = parent->begin(); it != parent->end(); ++it) - { - if (node == &(*it)) - break; - } - - if (it == parent->begin()) - node = parent; - else - node = &(--it)->get_node(0); - return *this; - } - - base_const_iterator operator++(int) - { - base_const_iterator tmp = *this; - operator++(); - return tmp; - } - - protected : - - const subtree* node; - }; - - class const_iterator : public base_const_iterator - { - public : - typedef std::forward_iterator_tag iterator_category; - typedef const subtree value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef const subtree* pointer; - typedef const subtree& reference; - - const_iterator() : base_const_iterator() {} - const_iterator(const subtree* n): base_const_iterator(n) {} - const_iterator& operator=(const const_iterator& org) - { base_const_iterator::operator=(org); return *this; } - - const subtree& operator*(void) { return *node; } - const subtree* operator->(void) { return node; } - }; - - class embedded_const_iterator : public base_const_iterator - { - public : - typedef std::forward_iterator_tag iterator_category; - typedef const T value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef const T* pointer; - typedef const T& reference; - - embedded_const_iterator() : base_const_iterator() {} - embedded_const_iterator(const subtree* n): base_const_iterator(n) {} - embedded_const_iterator& operator=(const embedded_const_iterator& org) - { base_const_iterator::operator=(org); return *this; } - - embedded_const_iterator operator+(size_t n) const - { - embedded_const_iterator tmp = *this; - - for(;n != 0; --n) - { - ++tmp; - } - - return tmp; - } - - const T& operator*(void) const { return **node; } - const T* operator->(void) const { return node->operator->(); } - }; - - /* Iterator access */ - - iterator begin(void) { return iterator(&operator[](0)); } - const_iterator begin(void) const { return const_iterator(&operator[](0)); } - iterator end(void) { return iterator(0); } - const_iterator end(void) const { return const_iterator(0);} - - embedded_iterator ebegin(void) { return embedded_iterator(&operator[](0)); } - embedded_const_iterator ebegin(void) const { return embedded_const_iterator(&operator[](0)); } - embedded_iterator eend(void) { return embedded_iterator(0); } - embedded_const_iterator eend(void) const { return embedded_const_iterator(0);} - - bool empty(void) const { return size() == 0; } - bool valid(void) const { return pushed.empty(); } - - /* push_back */ - - void push_back(const parse_tree& tree) - { - if (!empty()) - pushed.push_back(_root); - - _root = tree.back(); - } - - void push_back(const T& t) - { - if (!empty()) - pushed.push_back(_root); - - _root = t; - - for (subtree::iterator it = _root.begin(); it != _root.end(); it++) - { - *it = pushed.back(); - pushed.pop_back(); - } - - } - - /* Access to subtrees */ - - subtree& back(void) { return _root; } - const subtree& back(void) const { return _root; } - subtree& root(void) { return _root; } - const subtree& root(void) const { return _root; } - - subtree& front(void) { return _root[0]; } - const subtree& front(void) const { return _root[0]; } - - subtree& operator[](size_t i) - { return const_cast(_root.get_node(i)); } - const subtree& operator[](size_t i) const - { return _root.get_node(i); } - - subtree& get_cumulative(size_t i) - { return const_cast(_root.get_cumulative(i)); } - const subtree& get_cumulative(size_t i) const - { return get_cumulative(i); } - - private : - - parse_tree& copy(const parse_tree& org) - { - _root = org._root; - pushed = org.pushed; - - return *this; - } - - parse_tree& copy(const subtree& sub) - { _root = sub; pushed.resize(0); return *this; } - - subtree _root; - std::vector pushed; -}; // end class parse_tree - - -} // end namespace gp_parse_tree - -namespace std -{ // for use with stlport on MSVC - -template inline -std::forward_iterator_tag iterator_category(gp_parse_tree::parse_tree::embedded_iterator) -{ - return std::forward_iterator_tag(); -} - -template inline -ptrdiff_t* distance_type(gp_parse_tree::parse_tree::embedded_iterator) -{ - return 0; -} - -template inline -std::forward_iterator_tag iterator_category(gp_parse_tree::parse_tree::iterator) -{ - return std::forward_iterator_tag(); -} - -template inline -ptrdiff_t* distance_type(gp_parse_tree::parse_tree::iterator) -{ - return 0; -} - -// Put customized swaps also in std... - -template inline -void swap(gp_parse_tree::parse_tree& a, gp_parse_tree::parse_tree& b) -{ - a.swap(b); -} - -template inline -void iter_swap(vector >::iterator a, vector > b) -{ - a->swap(*b); -} - - -} // namespace std - - -#endif \ No newline at end of file +#ifndef PARSE_TREE_HH +#define PARSE_TREE_HH + +/** + + * Parse_tree and subtree classes + * (c) Maarten Keijzer 1999 + + * These classes may be used for educational and + * other non-commercial purposes only. Even if I + * wanted to, I am not at liberty to place this file + * under the GNU Lesser Public Library License, as this + * would limit my and my institution's freedom to use + * this file in closed-source software. + + * This material is provided "as is", with absolutely no warranty expressed + * or implied. Any use is at your own risk. + * + * Permission to use or copy this software for non-commercial purpose is hereby granted + * without fee, provided the above notices are retained on all copies. + * Permission to modify the code and to distribute modified code is granted, + * provided the above notices are retained, and a notice that the code was + * modified is included with the above copyright notice. + * + + + Usage information. + + class Node (your node in the tree) must have the following implemented: + + ****** Arity ****** + + int arity(void) const + + Note: the default constructor of a Node should provide a + Node with arity 0! + + ****** Evaluation ****** + + A parse_tree is evaluated through one of it's apply() members: + + 1) parse_tree::apply(void) + + is the simplest evaluation, it will call + + RetVal Node::operator()(subtree::const_iterator) + + 2) parse_tree::apply(It values) + + will call: + + RetVal Node::operator()(subtree<... , It values) + + where It is whatever type you desire (most of the time + this will be a vector containing the values of your + variables); + + 3) parse_tree::apply(It values, It2 moreValues) + + will call: + + RetVal Node::operator()(subtree<... , It values, It2 moreValues) + + although I do not see the immediate use of this, however... + + 4) parse_tree::apply(It values, It2 args, It3 adfs) + + that calls: + + RetVal Node::operator()(subtree<... , It values, It2 args, It3 adfs) + + can be useful for implementing adfs. + + + In general it is a good idea to leave the specifics of the + arguments open so that different ways of evaluation remain + possible. Implement the simplest eval as: + + template + RetVal operator()(It begin) const + + ****** Internal Structure ****** + + A parse_tree has two template arguments: the Node and the ReturnValue + produced by evaluating the node. The structure of the tree is defined + through a subtree class that has the same two template arguments. + + The nodes are stored in a tree like : + + node4 + / \ + node3 node2 + / \ + node1 node0 + + where nodes 2 and 4 have arity 2 and nodes 0,1 and 3 arity 0 (terminals) + + The nodes are subtrees, containing the structure of the tree, together + with its size and depth. They contain a Node, the user defined template + argument. To access these nodes from a subtree, use operator-> or operator*. + + The numbers behind the nodes define a reverse-polish or postfix + traversel through the tree. The parse_tree defines iterators + on the tree such that + + tree.begin() points at the subtree at node0 and + tree.back() returns the subtree at node4, the complete tree + + Likewise operator[] is defined on the tree, such that: + + tree[0] will return the subtree at node0, while + tree[2] will return the subtree at node2 + + Assigments of subtrees is protected so that the code: + + tree[2] = tree[0]; + + will not crash and result in a tree structured as: + + node4 + / \ + node3 node0 + + Note that the rank numbers no longer specify their place in the tree: + + tree[0] still points at node0, but + tree[1] now points to node3 and + tree[2] points at the root node4 + + Embedded iterators are implemented to iterate over nodes rather + than subtrees. So an easy way to copy your tree to a vector is: + + vector vec(tree.size()); + copy(tree.ebegin(), tree.eend(), vec.begin()); + + You can also copy it to an ostream_iterator with this + technique, given that your Node implements an appropriate + operator<<. Reinitializing a tree with the vector is also + simple: + + tree.clear(); + copy(vec.begin(), vec.end(), back_inserter(tree)); + + Note that the back_inserter must be used as there is no + resize member in the parse_tree. back_inserter will use + the push_back member from the parse_tree + +*/ + +#include +#include // for swap + +#ifdef _MSC_VER +#pragma warning(disable : 4786) // disable this nagging warning about the limitations of the mirkosoft debugger +#endif + +namespace gp_parse_tree +{ + +#include "node_pool.h" + + +template +inline void do_the_swap(T& a, T& b) +{ + T tmp = a; + a = b; + b = tmp; +} + +template class parse_tree +{ + public : + +class subtree +{ + +// a bit nasty way to use a pool allocator (which would otherwise use slooow new and delete) +#if (defined(__GNUC__) || defined(_MSC_VER)) && !defined(_MT) + Node_alloc node_allocator; + Tree_alloc tree_allocator; +#else + Standard_Node_alloc node_allocator; + Standard_alloc tree_allocator; +#endif + +public : + + typedef subtree* iterator; + typedef const subtree* const_iterator; + //typedef std::vector::const_reverse_iterator const_reverse_iterator; + + /* Constructors, assignments */ + + subtree(void) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) + {} + subtree(const subtree& s) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) + { copy(s); } + subtree(const T& t) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) + { copy(t); } + + template + subtree(It b, It e) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) + { // initialize in prefix way for efficiency reasons + init(b, --e); + } + + virtual ~subtree(void) { tree_allocator.deallocate(args, arity()); node_allocator.deallocate(content); } + + subtree& operator=(const subtree& s) + { + if (s.get_root() == get_root()) + { // from the same tree, maybe a child. Don't take any chances + subtree anotherS = s; + return copy(anotherS); + } + + return copy(s); + } + + subtree& operator=(const T& t) { return copy(t); } + + /* Access to the nodes */ + + T& operator*(void) { return *content; } + const T& operator*(void) const { return *content; } + T* operator->(void) { return content; } + const T* operator->(void) const { return content; } + + /* Equality, inequality check, Node needs to implement operator== */ + + bool operator==(const subtree& other) const + { + if (! (*content == *other.content)) + return false; + + for (int i = 0; i < arity(); i++) + { + if (!(args[i] == other.args[i])) + return false; + } + + return true; + } + + bool operator !=(const subtree& other) const + { + return !operator==(other); + } + + /* Arity */ + int arity(void) const { return content->arity(); } + + /* Evaluation with an increasing amount of user defined arguments */ + template + RetVal apply(RetVal v) const { return (*content)(v, begin()); } + + template + RetVal apply(RetVal v, It values) const { return (*content)(v, begin(), values); } + + template + RetVal apply(RetVal v, It values, It2 moreValues) const + { return (*content)(v, begin(), values, moreValues); } + + template + RetVal apply(RetVal v, It values, It2 moreValues, It3 evenMoreValues) const + { return (*content)(v, begin(), values, moreValues, evenMoreValues); } + + + /* Iterators */ + + iterator begin(void) { return args; } + const_iterator begin(void) const { return args; } + + iterator end(void) { return args + arity(); } + const_iterator end(void) const { return args + arity(); } + + subtree& operator[](int i) { return *(begin() + i); } + const subtree& operator[](int i) const { return *(begin() + i); } + + /* Some statistics */ + + size_t size(void) const { return _size; } + + size_t cumulative_size(void) const { return _cumulative_size; } + size_t depth(void) const { return _depth; } + + const subtree& select_cumulative(size_t which) const + { return imp_select_cumulative(which); } + + subtree& select_cumulative(size_t which) + { return const_cast(imp_select_cumulative(which)); } + + subtree& get_node(size_t which) + { return const_cast(imp_get_node(which));} + const subtree& get_node(size_t which) const + { return imp_get_node(which); } + + subtree* get_parent(void) { return parent; } + const subtree* get_parent(void) const { return parent; } + + void clear(void) + { tree_allocator.deallocate(args, arity()); args = 0; *content = T(); parent = 0; _cumulative_size = 0; _depth = 0; _size = 0; } + + void swap(subtree& y) + { + do_the_swap(content, y.content); + do_the_swap(args, y.args); + do_the_swap(parent, y.parent); + + do_the_swap(_cumulative_size, y._cumulative_size); + do_the_swap(_depth, y._depth); + do_the_swap(_size, y._size); + updateAfterInsert(); + } + + friend void swap(subtree& x, subtree& y) + { + x.swap(y); + } + +protected : + + virtual void updateAfterInsert(void) + { + _depth = 0; + _size = 1; + _cumulative_size = 0; + + for (iterator it = begin(); it != end(); ++it) + { + _size += it->size(); + _cumulative_size += it->_cumulative_size; + _depth = it->_depth > _depth? it->_depth: _depth; + } + _cumulative_size += _size; + _depth++; + + if (parent) + parent->updateAfterInsert(); + } + +private : + + const subtree& imp_select_cumulative(size_t which) const + { + if (which >= (_cumulative_size - size())) + return *this; + // else + + for (int i = arity() - 1; i >= 0; --i) + { + if (which < args[i]._cumulative_size) + return args[i].imp_select_cumulative(which); + which -= args[i]._cumulative_size; + } + + return *this; // error! + } + + const subtree& imp_get_node(size_t which) const + { + if (which == size() - 1) + return *this; + + for (int i = arity() - 1; i >= 0; --i) + { + unsigned c_size = args[i].size(); + if (which < c_size) + return args[i].imp_get_node(which); + which -= c_size; + } + + return *this; // error! + } + + const subtree* get_root(void) const + { + if (parent == 0) + return this; + // else + + return parent->get_root(); + } + + subtree& copy(const subtree& s) + { + int oldArity = arity(); + + disown(); + + int ar = s.arity(); + + if (ar != oldArity) + { + tree_allocator.deallocate(args, oldArity); + + args = tree_allocator.allocate(ar); + + //if (ar > 0) + // args = new subtree [ar]; + //else + // args = 0; + } + + switch(ar) + { + case 3 : args[2].copy(s.args[2]); // no break! + case 2 : args[1].copy(s.args[1]); + case 1 : args[0].copy(s.args[0]); break; + case 0 : break; + default : + { + for (int i = 0; i < ar; ++i) + { + args[i].copy(s.args[i]); + } + } + } + + *content = *s.content; + + adopt(); + updateAfterInsert(); + return *this; + } + + subtree& copy(const T& t) + { + int oldArity = arity(); + + if (content != &t) + *content = t; + else + oldArity = -1; + + int ar = arity(); + + if (ar != oldArity) + { + if (oldArity != -1) + tree_allocator.deallocate(args, oldArity); + + args = tree_allocator.allocate(ar); + + //if (ar > 0) + // args = new subtree [ar]; + //else + // args = 0; + } + + adopt(); + updateAfterInsert(); + return *this; + } + + void disown(void) + { + switch(arity()) + { + case 3 : args[2].parent = 0; // no break! + case 2 : args[1].parent = 0; + case 1 : args[0].parent = 0; break; + case 0 : break; + default : + { + for (iterator it = begin(); it != end(); ++it) + { + it->parent = 0; + } + } + } + + } + + void adopt(void) + { + switch(arity()) + { + case 3 : args[2].parent = this; // no break! + case 2 : args[1].parent = this; + case 1 : args[0].parent = this; break; + case 0 : break; + default : + { + for (iterator it = begin(); it != end(); ++it) + { + it->parent = this; + } + } + } + } + + template + void init(It b, It& last) + { + *this = *last; + +#ifndef NDEBUG + if (last == b && arity() > 0) + { + throw "subtree::init()"; + } +#endif + + for (int i = 0; i < arity(); ++i) + { + args[i].parent = 0; + args[i].init(b, --last); + args[i].parent = this; + } + + updateAfterInsert(); + } + + T* content; + subtree* args; + subtree* parent; + + size_t _cumulative_size; + size_t _depth; + size_t _size; +}; + +// Continuing with parse_tree + + typedef T value_type; + + /* Constructors and Assignments */ + + parse_tree(void) : _root(), pushed() {} + parse_tree(const parse_tree& org) : _root(org._root), pushed(org.pushed) { } + parse_tree(const subtree& sub) : _root(sub), pushed() { } + + template + parse_tree(It b, It e) : _root(b, e), pushed() {} + + virtual ~parse_tree(void) {} + + parse_tree& operator=(const parse_tree& org) { return copy(org); } + parse_tree& operator=(const subtree& sub) + { return copy(sub); } + + + /* Equality and inequality */ + + bool operator==(const parse_tree& other) const + { return _root == other._root; } + + bool operator !=(const parse_tree& other) const + { return !operator==(other); } + + /* Simple tree statistics */ + + size_t size(void) const { return _root.size(); } + size_t depth(void) const { return _root.depth(); } + void clear(void) { _root.clear(); pushed.resize(0); } + + /* Evaluation (application), with an increasing number of user defined arguments */ + + template + RetVal apply(RetVal v) const + { return _root.apply(v); } + + template + RetVal apply(RetVal v, It varValues) const + { return _root.apply(v, varValues); } + + template + RetVal apply(RetVal v, It varValues, It2 moreValues) const + { return _root.apply(v, varValues, moreValues); } + + template + RetVal apply(RetVal v, It varValues, It2 moreValues, It3 evenMoreValues) const + { return _root.apply(v, varValues, moreValues, evenMoreValues); } + + /* Customized Swap */ + void swap(parse_tree& other) + { + do_the_swap(pushed, other.pushed); + _root.swap(other._root); + } + + /* Definitions of the iterators */ + + class base_iterator + { + public : + + base_iterator() {} + base_iterator(subtree* n) { node = n; } + + base_iterator& operator=(const base_iterator& org) + { node = org.node; return *this; } + + bool operator==(const base_iterator& org) const + { return node == org.node; } + bool operator!=(const base_iterator& org) const + { return !operator==(org); } + + base_iterator operator+(size_t n) const + { + base_iterator tmp = *this; + + for(;n != 0; --n) + { + ++tmp; + } + + return tmp; + } + + base_iterator& operator++(void) + { + subtree* parent = node->get_parent(); + + if (parent == 0) + { + node = 0; + return *this; + } + // else + subtree::iterator it; + for (it = parent->begin(); it != parent->end(); ++it) + { + if (node == &(*it)) + break; + } + + if (it == parent->begin()) + node = parent; + else + { + node = &(--it)->get_node(0); + } + + return *this; + } + + base_iterator operator++(int) + { + base_iterator tmp = *this; + operator++(); + return tmp; + } + + protected : + subtree* node; + }; + + class iterator : public base_iterator + { + public : + typedef std::forward_iterator_tag iterator_category; + typedef subtree value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef subtree* pointer; + typedef subtree& reference; + + iterator() : base_iterator() {} + iterator(subtree* n): base_iterator(n) {} + iterator& operator=(const iterator& org) + { base_iterator::operator=(org); return *this; } + + subtree& operator*(void) { return *node; } + subtree* operator->(void) { return node; } + }; + + class embedded_iterator : public base_iterator + { + public : + typedef std::forward_iterator_tag iterator_category; + typedef T value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef T* pointer; + typedef T& reference; + + embedded_iterator() : base_iterator() {} + embedded_iterator(subtree* n): base_iterator(n) {} + embedded_iterator& operator=(const embedded_iterator& org) + { base_iterator::operator=(org); return *this; } + + T& operator*(void) { return **node; } + T* operator->(void) { return &**node; } + }; + + class base_const_iterator + { + public : + base_const_iterator() {} + base_const_iterator(const subtree* n) { node = n; } + + base_const_iterator& operator=(const base_const_iterator& org) + { node = org.node; return *this; } + + bool operator==(const base_const_iterator& org) const + { return node == org.node; } + bool operator!=(const base_const_iterator& org) const + { return !operator==(org); } + + base_const_iterator& operator++(void) + { + const subtree* parent = node->get_parent(); + + if (parent == 0) + { + node = 0; + return *this; + } + // else + subtree::const_iterator it; + + for (it = parent->begin(); it != parent->end(); ++it) + { + if (node == &(*it)) + break; + } + + if (it == parent->begin()) + node = parent; + else + node = &(--it)->get_node(0); + return *this; + } + + base_const_iterator operator++(int) + { + base_const_iterator tmp = *this; + operator++(); + return tmp; + } + + protected : + + const subtree* node; + }; + + class const_iterator : public base_const_iterator + { + public : + typedef std::forward_iterator_tag iterator_category; + typedef const subtree value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef const subtree* pointer; + typedef const subtree& reference; + + const_iterator() : base_const_iterator() {} + const_iterator(const subtree* n): base_const_iterator(n) {} + const_iterator& operator=(const const_iterator& org) + { base_const_iterator::operator=(org); return *this; } + + const subtree& operator*(void) { return *node; } + const subtree* operator->(void) { return node; } + }; + + class embedded_const_iterator : public base_const_iterator + { + public : + typedef std::forward_iterator_tag iterator_category; + typedef const T value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef const T* pointer; + typedef const T& reference; + + embedded_const_iterator() : base_const_iterator() {} + embedded_const_iterator(const subtree* n): base_const_iterator(n) {} + embedded_const_iterator& operator=(const embedded_const_iterator& org) + { base_const_iterator::operator=(org); return *this; } + + embedded_const_iterator operator+(size_t n) const + { + embedded_const_iterator tmp = *this; + + for(;n != 0; --n) + { + ++tmp; + } + + return tmp; + } + + const T& operator*(void) const { return **node; } + const T* operator->(void) const { return node->operator->(); } + }; + + /* Iterator access */ + + iterator begin(void) { return iterator(&operator[](0)); } + const_iterator begin(void) const { return const_iterator(&operator[](0)); } + iterator end(void) { return iterator(0); } + const_iterator end(void) const { return const_iterator(0);} + + embedded_iterator ebegin(void) { return embedded_iterator(&operator[](0)); } + embedded_const_iterator ebegin(void) const { return embedded_const_iterator(&operator[](0)); } + embedded_iterator eend(void) { return embedded_iterator(0); } + embedded_const_iterator eend(void) const { return embedded_const_iterator(0);} + + bool empty(void) const { return size() == 0; } + bool valid(void) const { return pushed.empty(); } + + /* push_back */ + + void push_back(const parse_tree& tree) + { + if (!empty()) + pushed.push_back(_root); + + _root = tree.back(); + } + + void push_back(const T& t) + { + if (!empty()) + pushed.push_back(_root); + + _root = t; + + for (subtree::iterator it = _root.begin(); it != _root.end(); it++) + { + *it = pushed.back(); + pushed.pop_back(); + } + + } + + /* Access to subtrees */ + + subtree& back(void) { return _root; } + const subtree& back(void) const { return _root; } + subtree& root(void) { return _root; } + const subtree& root(void) const { return _root; } + + subtree& front(void) { return _root[0]; } + const subtree& front(void) const { return _root[0]; } + + subtree& operator[](size_t i) + { return const_cast(_root.get_node(i)); } + const subtree& operator[](size_t i) const + { return _root.get_node(i); } + + subtree& get_cumulative(size_t i) + { return const_cast(_root.get_cumulative(i)); } + const subtree& get_cumulative(size_t i) const + { return get_cumulative(i); } + + private : + + parse_tree& copy(const parse_tree& org) + { + _root = org._root; + pushed = org.pushed; + + return *this; + } + + parse_tree& copy(const subtree& sub) + { _root = sub; pushed.resize(0); return *this; } + + subtree _root; + std::vector pushed; +}; // end class parse_tree + + +} // end namespace gp_parse_tree + +namespace std +{ // for use with stlport on MSVC + +template inline +std::forward_iterator_tag iterator_category(gp_parse_tree::parse_tree::embedded_iterator) +{ + return std::forward_iterator_tag(); +} + +template inline +ptrdiff_t* distance_type(gp_parse_tree::parse_tree::embedded_iterator) +{ + return 0; +} + +template inline +std::forward_iterator_tag iterator_category(gp_parse_tree::parse_tree::iterator) +{ + return std::forward_iterator_tag(); +} + +template inline +ptrdiff_t* distance_type(gp_parse_tree::parse_tree::iterator) +{ + return 0; +} + +// Put customized swaps also in std... + +template inline +void swap(gp_parse_tree::parse_tree& a, gp_parse_tree::parse_tree& b) +{ + a.swap(b); +} + +template inline +void iter_swap(vector >::iterator a, vector > b) +{ + a->swap(*b); +} + + +} // namespace std + + +#endif diff --git a/eo/src/compatibility.h b/eo/src/compatibility.h index 7a4f5364..1297fc9e 100644 --- a/eo/src/compatibility.h +++ b/eo/src/compatibility.h @@ -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 -#include - -#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 - -#ifdef min -#undef min -#undef max // as they come in pairs -#endif - -// add min and max to std... -namespace std -{ - template T min(const T& a, const T& b) - { - if(a < b) - return a; - // else - return b; - } - - template T max(const T& a, const T& b) - { - if(a > b) - return a; - // else - return b; - } -} - -#endif // _MSC_VER - -#endif \ No newline at end of file +/* -*- 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 +#include + +#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 + +#ifdef min +#undef min +#undef max // as they come in pairs +#endif + +// add min and max to std... +namespace std +{ + template T min(const T& a, const T& b) + { + if(a < b) + return a; + // else + return b; + } + + template T max(const T& a, const T& b) + { + if(a > b) + return a; + // else + return b; + } +} + +#endif // _MSC_VER + +#endif diff --git a/eo/src/eoAged.h b/eo/src/eoAged.h index 2e37c1a1..3211791d 100644 --- a/eo/src/eoAged.h +++ b/eo/src/eoAged.h @@ -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 // istream, ostream -#include // 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 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 // istream, ostream +#include // 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 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 + diff --git a/eo/src/eoAtomCreep.h b/eo/src/eoAtomCreep.h index 2fc7d676..b31c56ba 100644 --- a/eo/src/eoAtomCreep.h +++ b/eo/src/eoAtomCreep.h @@ -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 -#include - -/** With uniform probability, decrements or increments by one the value. - The value type must admit post increment and decrement. -*/ -template -class eoAtomCreep: public eoAtomMutator { -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 +#include + +/** With uniform probability, decrements or increments by one the value. + The value type must admit post increment and decrement. +*/ +template +class eoAtomCreep: public eoAtomMutator { +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 + diff --git a/eo/src/eoAtomMutation.h b/eo/src/eoAtomMutation.h index c4ff91af..977f6b50 100644 --- a/eo/src/eoAtomMutation.h +++ b/eo/src/eoAtomMutation.h @@ -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 - -// EO includes -#include -#include -#include -#include - -/** 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 eoAtomMutation: public eoMonOp { -public: - -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - /// - eoAtomMutation(const eoAtomMutator& _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& 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 + +// EO includes +#include +#include +#include +#include + +/** 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 eoAtomMutation: public eoMonOp { +public: + +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + /// + eoAtomMutation(const eoAtomMutator& _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& atomMutator; +}; + + +#endif + diff --git a/eo/src/eoAtomMutator.h b/eo/src/eoAtomMutator.h index 97510c58..7303f16d 100644 --- a/eo/src/eoAtomMutator.h +++ b/eo/src/eoAtomMutator.h @@ -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 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 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 + diff --git a/eo/src/eoBackInserter.h b/eo/src/eoBackInserter.h index c7d1de61..5e9faef7 100644 --- a/eo/src/eoBackInserter.h +++ b/eo/src/eoBackInserter.h @@ -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 eoBackInserter : public eoPopInserter -{ - public : - - eoBackInserter(void) : eoPopInserter() {} - - void insert(const EOT& _eot) - { - pop().push_back(_eot); - } - - string className(void) const { return "eoBackInserter"; } - -}; - -#endif \ No newline at end of file +/* -*- 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 eoBackInserter : public eoPopInserter +{ + public : + + eoBackInserter(void) : eoPopInserter() {} + + void insert(const EOT& _eot) + { + pop().push_back(_eot); + } + + string className(void) const { return "eoBackInserter"; } + +}; + +#endif diff --git a/eo/src/eoBitOp.h b/eo/src/eoBitOp.h index ca1ee734..78337fbb 100644 --- a/eo/src/eoBitOp.h +++ b/eo/src/eoBitOp.h @@ -1,324 +1,325 @@ -//----------------------------------------------------------------------------- -// eoBitOp.h -//----------------------------------------------------------------------------- - -#ifndef eoBitOp_h -#define eoBitOp_h - -//----------------------------------------------------------------------------- - -#include // swap_ranges -#include // eoUniform -#include // eoBin -#include // 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 eoBinRandom: public eoMonOp -{ - 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 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 eoBinBitFlip: public eoMonOp -{ - 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 uniform(0, chrom.size()); - unsigned i = uniform(); - chrom[i] = (chrom[i]) ? false : true; - } -}; - - -/** eoBinMutation --> classical mutation */ - -template class eoBinMutation: public eoMonOp -{ - 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 uniform; -}; - - -/** eoBinInversion: inverts the bits of the chromosome between an interval */ - -template class eoBinInversion: public eoMonOp -{ - 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 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 eoBinNext: public eoMonOp -{ - 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 eoBinPrev: public eoMonOp -{ - 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 eoBinCrossover: public eoQuadraticOp -{ - 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 uniform(1, min(chrom1.size(), chrom2.size())); - swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin()); - } -}; - - -/** eoBinNxOver --> n-point crossover */ - -template class eoBinNxOver: public eoQuadraticOp -{ - 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 points(max_size, false); - eoUniform 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 eoBinGxOver: public eoQuadraticOp -{ - 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 points(max_genes, false); - eoUniform 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 // swap_ranges +#include // eoUniform +#include // eoBin +#include // 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 eoBinRandom: public eoMonOp +{ + 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 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 eoBinBitFlip: public eoMonOp +{ + 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 uniform(0, chrom.size()); + unsigned i = uniform(); + chrom[i] = (chrom[i]) ? false : true; + } +}; + + +/** eoBinMutation --> classical mutation */ + +template class eoBinMutation: public eoMonOp +{ + 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 uniform; +}; + + +/** eoBinInversion: inverts the bits of the chromosome between an interval */ + +template class eoBinInversion: public eoMonOp +{ + 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 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 eoBinNext: public eoMonOp +{ + 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 eoBinPrev: public eoMonOp +{ + 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 eoBinCrossover: public eoQuadraticOp +{ + 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 uniform(1, min(chrom1.size(), chrom2.size())); + swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin()); + } +}; + + +/** eoBinNxOver --> n-point crossover */ + +template class eoBinNxOver: public eoQuadraticOp +{ + 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 points(max_size, false); + eoUniform 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 eoBinGxOver: public eoQuadraticOp +{ + 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 points(max_genes, false); + eoUniform 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 + diff --git a/eo/src/eoBitOpFactory.h b/eo/src/eoBitOpFactory.h index b44a5506..8d70c7e4 100644 --- a/eo/src/eoBitOpFactory.h +++ b/eo/src/eoBitOpFactory.h @@ -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 -#include - -//----------------------------------------------------------------------------- - -/** 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 { - -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* make(istream& _is) { - eoOp * opPtr = NULL; - try { - opPtr = eoOpFactory::make( _is ); - } catch ( const string& objectTypeStr ) { - if ( objectTypeStr == "eoBinRandom") { - opPtr = new eoBinRandom(); - } - if ( objectTypeStr == "eoBinBitFlip" ) { - opPtr = new eoBinBitFlip( ); - } - if ( objectTypeStr == "eoBinMutation" ) { - float rate; - _is >> rate; - opPtr = new eoBinMutation( rate ); - } - if ( objectTypeStr == "eoBinInversion" ) { - opPtr = new eoBinInversion( ); - } - if ( objectTypeStr == "eoBinNext" ) { - opPtr = new eoBinNext( ); - } - if ( objectTypeStr == "eoBinPrev" ) { - opPtr = new eoBinPrev( ); - } - if ( objectTypeStr == "eoBinNext" ) { - opPtr = new eoBinNext( ); - } - if ( objectTypeStr == "eoBinCrossover" ) { - opPtr = new eoBinCrossover( ); - } - if ( objectTypeStr == "eoBinNxOver" ) { - unsigned nPoints; - _is >> nPoints; - opPtr = new eoBinNxOver( nPoints ); - } - if ( objectTypeStr == "eoBinGxOver" ) { - unsigned geneSize, nPoints; - _is >> geneSize >> nPoints; - opPtr = new eoBinGxOver( geneSize, nPoints ); - } - if ( objectTypeStr == "eoBinUxOver" ) { - float rate; - _is >> rate; - opPtr = new eoBinUxOver( 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 +#include + +//----------------------------------------------------------------------------- + +/** 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 { + +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* make(istream& _is) { + eoOp * opPtr = NULL; + try { + opPtr = eoOpFactory::make( _is ); + } catch ( const string& objectTypeStr ) { + if ( objectTypeStr == "eoBinRandom") { + opPtr = new eoBinRandom(); + } + if ( objectTypeStr == "eoBinBitFlip" ) { + opPtr = new eoBinBitFlip( ); + } + if ( objectTypeStr == "eoBinMutation" ) { + float rate; + _is >> rate; + opPtr = new eoBinMutation( rate ); + } + if ( objectTypeStr == "eoBinInversion" ) { + opPtr = new eoBinInversion( ); + } + if ( objectTypeStr == "eoBinNext" ) { + opPtr = new eoBinNext( ); + } + if ( objectTypeStr == "eoBinPrev" ) { + opPtr = new eoBinPrev( ); + } + if ( objectTypeStr == "eoBinNext" ) { + opPtr = new eoBinNext( ); + } + if ( objectTypeStr == "eoBinCrossover" ) { + opPtr = new eoBinCrossover( ); + } + if ( objectTypeStr == "eoBinNxOver" ) { + unsigned nPoints; + _is >> nPoints; + opPtr = new eoBinNxOver( nPoints ); + } + if ( objectTypeStr == "eoBinGxOver" ) { + unsigned geneSize, nPoints; + _is >> geneSize >> nPoints; + opPtr = new eoBinGxOver( geneSize, nPoints ); + } + if ( objectTypeStr == "eoBinUxOver" ) { + float rate; + _is >> rate; + opPtr = new eoBinUxOver( rate ); + } + if ( !opPtr ) { // to be caught by the upper level + throw objectTypeStr; + } + } + return opPtr; + }; + + +}; + + +#endif _EOBITOPFACTORY_H + diff --git a/eo/src/eoBreeder.h b/eo/src/eoBreeder.h index e94e815e..24fa83e5 100644 --- a/eo/src/eoBreeder.h +++ b/eo/src/eoBreeder.h @@ -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 -#include // eoUniform -#include // eoOp, eoMonOp, eoBinOp -#include // eoPop -#include // eoTransform -#include // 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 eoBreeder: public eoMonPopOp -{ - public: - /// Default constructor. - eoBreeder( eoOpSelector& _opSel): opSel( _opSel ) {} - - /// Destructor. - virtual ~eoBreeder() {} - - /** - * Transforms a population. - * @param pop The population to be transformed. - */ - void operator()(eoPop& pop) - { - size_t orgsize = pop.size(); - - for (unsigned i = 0; i < pop.size(); i++) { - eoOp* op = opSel.Op(); - switch (op->getType()) { - case eoOp::unary: - { - eoMonOp* monop = static_cast* >(op); - (*monop)( pop[i] ); - break; - } - case eoOp::binary: - { - eoBinOp* binop = static_cast* >(op); - eoUniform u(0, pop.size() ); - (*binop)(pop[i], pop[ u() ] ); - break; - } - case eoOp::quadratic: - { - eoQuadraticOp* Qop = static_cast* >(op); - - eoUniform u(0, pop.size() ); - (*Qop)(pop[i], pop[ u() ] ); - break; - } - case eoOp::general : - { - eoGeneralOp* Gop = static_cast* >(op); - - eoRandomIndiSelector selector; - eoBackInserter inserter; - - (*Gop)(selector(pop, orgsize, i), inserter(pop)); - break; - } - } - } - }; - - /// The class name. - string classname() const { return "eoBreeder"; } - - private: - eoOpSelector& 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 +#include // eoUniform +#include // eoOp, eoMonOp, eoBinOp +#include // eoPop +#include // eoTransform +#include // 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 eoBreeder: public eoMonPopOp +{ + public: + /// Default constructor. + eoBreeder( eoOpSelector& _opSel): opSel( _opSel ) {} + + /// Destructor. + virtual ~eoBreeder() {} + + /** + * Transforms a population. + * @param pop The population to be transformed. + */ + void operator()(eoPop& pop) + { + size_t orgsize = pop.size(); + + for (unsigned i = 0; i < pop.size(); i++) { + eoOp* op = opSel.Op(); + switch (op->getType()) { + case eoOp::unary: + { + eoMonOp* monop = static_cast* >(op); + (*monop)( pop[i] ); + break; + } + case eoOp::binary: + { + eoBinOp* binop = static_cast* >(op); + eoUniform u(0, pop.size() ); + (*binop)(pop[i], pop[ u() ] ); + break; + } + case eoOp::quadratic: + { + eoQuadraticOp* Qop = static_cast* >(op); + + eoUniform u(0, pop.size() ); + (*Qop)(pop[i], pop[ u() ] ); + break; + } + case eoOp::general : + { + eoGeneralOp* Gop = static_cast* >(op); + + eoRandomIndiSelector selector; + eoBackInserter inserter; + + (*Gop)(selector(pop, orgsize, i), inserter(pop)); + break; + } + } + } + }; + + /// The class name. + string classname() const { return "eoBreeder"; } + + private: + eoOpSelector& opSel; + +}; + +//----------------------------------------------------------------------------- + +#endif eoBreeder_h + diff --git a/eo/src/eoData.h b/eo/src/eoData.h index f760ea36..1ba35860 100644 --- a/eo/src/eoData.h +++ b/eo/src/eoData.h @@ -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 -#include // set -#include // string - -using namespace std; - - -#ifdef _MSC_VER - #include // MAXDOUBLE - #define MAXFLOAT numeric_limits::max() - #define MINFLOAT numeric_limits::min() - #define MAXDOUBLE numeric_limits::max() - #define MAXINT numeric_limits::max() -#else - #include + 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 +#include // set +#include // string + +using namespace std; + + +#ifdef _MSC_VER + #include // MAXDOUBLE + #define MAXFLOAT numeric_limits::max() + #define MINFLOAT numeric_limits::min() + #define MAXDOUBLE numeric_limits::max() + #define MAXINT numeric_limits::max() +#else + #include #include #ifndef _WIN32 // should be the define for UN*X flavours: _POSIX?? - #include + #include #endif - #ifndef MAXFLOAT - #define MAXFLOAT (float)1e127 - #define MAXDOUBLE (double)1.79769313486231570e+308 - #define MAXINT 2147483647 - #endif -#endif - -#ifndef _MSC_VER -#include -#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 +#define _isnan isnan +#endif + +//----------------------------------------------------------------------------- + +#endif EODATA_H + diff --git a/eo/src/eoDetTournament.h b/eo/src/eoDetTournament.h index b4a5bec9..577f0c3b 100644 --- a/eo/src/eoDetTournament.h +++ b/eo/src/eoDetTournament.h @@ -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 // -#include // accumulate -#include // eoPop eoSelect MINFLOAT -#include "selectors.h" - -//----------------------------------------------------------------------------- -/** eoDetTournament: a selection method that selects ONE individual by - deterministic tournament - -MS- 24/10/99 */ -//----------------------------------------------------------------------------- - -template class eoDetTournament: public eoSelectOne -{ - public: - /// (Default) Constructor. - eoDetTournament(unsigned _Tsize = 2 ):eoSelectOne(), Tsize(_Tsize) { - // consistency check - if (Tsize < 2) { - cout << "Warning, Tournament size should be >= 2\nAdjusted\n"; - Tsize = 2; - } - } - - virtual const EOT& operator()(const eoPop& 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 // +#include // accumulate +#include // eoPop eoSelect MINFLOAT +#include "selectors.h" + +//----------------------------------------------------------------------------- +/** eoDetTournament: a selection method that selects ONE individual by + deterministic tournament + -MS- 24/10/99 */ +//----------------------------------------------------------------------------- + +template class eoDetTournament: public eoSelectOne +{ + public: + /// (Default) Constructor. + eoDetTournament(unsigned _Tsize = 2 ):eoSelectOne(), Tsize(_Tsize) { + // consistency check + if (Tsize < 2) { + cout << "Warning, Tournament size should be >= 2\nAdjusted\n"; + Tsize = 2; + } + } + + virtual const EOT& operator()(const eoPop& pop) + { + return deterministic_tournament(pop, Tsize)(); + } + + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoDetTournament";}; + + private: + unsigned Tsize; +}; + +//----------------------------------------------------------------------------- + +#endif eoDetTournament_h + diff --git a/eo/src/eoDetTournamentIndiSelector.h b/eo/src/eoDetTournamentIndiSelector.h index 45ca2132..d5c35df4 100644 --- a/eo/src/eoDetTournamentIndiSelector.h +++ b/eo/src/eoDetTournamentIndiSelector.h @@ -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 eoDetTournamentIndiSelector : public eoPopIndiSelector -{ - public : - - eoDetTournamentIndiSelector(int _tournamentSize) - : eoPopIndiSelector(), - tournamentSize(_tournamentSize) - {} - - virtual ~eoDetTournamentIndiSelector(void) {} - - const EOT& do_select(void) - { - return *deterministic_tournament(begin(), end(), tournamentSize); - } - - private : - - int tournamentSize; -}; - -#endif \ No newline at end of file +/* -*- 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 eoDetTournamentIndiSelector : public eoPopIndiSelector +{ + public : + + eoDetTournamentIndiSelector(int _tournamentSize) + : eoPopIndiSelector(), + tournamentSize(_tournamentSize) + {} + + virtual ~eoDetTournamentIndiSelector(void) {} + + const EOT& do_select(void) + { + return *deterministic_tournament(begin(), end(), tournamentSize); + } + + private : + + int tournamentSize; +}; + +#endif diff --git a/eo/src/eoDetTournamentInserter.h b/eo/src/eoDetTournamentInserter.h index 21e77ae3..bdc1dd0a 100644 --- a/eo/src/eoDetTournamentInserter.h +++ b/eo/src/eoDetTournamentInserter.h @@ -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 eoDetTournamentInserter : public eoSteadyStateInserter -{ - public : - - eoDetTournamentInserter(eoEvalFunc& _eval, unsigned _t_size) : t_size(_t_size), eoSteadyStateInserter(_eval) - { - if (t_size < 2) - { // warning, error? - t_size = 2; - } - } - - void insert(const EOT& _eot) - { - EOT& eo = inverse_deterministic_tournament(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 \ No newline at end of file +/* -*- 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 eoDetTournamentInserter : public eoSteadyStateInserter +{ + public : + + eoDetTournamentInserter(eoEvalFunc& _eval, unsigned _t_size) : t_size(_t_size), eoSteadyStateInserter(_eval) + { + if (t_size < 2) + { // warning, error? + t_size = 2; + } + } + + void insert(const EOT& _eot) + { + EOT& eo = inverse_deterministic_tournament(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 diff --git a/eo/src/eoDup.h b/eo/src/eoDup.h index 7a13bd75..727db3c3 100644 --- a/eo/src/eoDup.h +++ b/eo/src/eoDup.h @@ -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 - -#include - -/// Dup or duplicate: duplicates a gene in a chromosome -template -class eoDup: public eoMonOp { -public: - /// - eoDup( ) - : eoMonOp< EOT >( ){}; - - /// needed virtual dtor - virtual ~eoDup() {}; - - /// - virtual void operator()( EOT& _eo ) const { - eoUniform 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 + +#include + +/// Dup or duplicate: duplicates a gene in a chromosome +template +class eoDup: public eoMonOp { +public: + /// + eoDup( ) + : eoMonOp< EOT >( ){}; + + /// needed virtual dtor + virtual ~eoDup() {}; + + /// + virtual void operator()( EOT& _eo ) const { + eoUniform 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 + diff --git a/eo/src/eoESChrom.h b/eo/src/eoESChrom.h index d8d87564..495a9ba6 100644 --- a/eo/src/eoESChrom.h +++ b/eo/src/eoESChrom.h @@ -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 // For vector<> -#include -#include -#include // for ostream - -// EO includes -#include - -/**@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 -class eoESChrom: public eoVector { -public: - /// Basic ctor - eoESChrom( ):eoVector() {}; - - /** 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& _rnd, eoRnd& _rndS ) - : eoVector( _size ){ - for ( iterator i = begin(); i != end(); i ++ ) { - i->val = _rnd(); - i->sigma = _rndS(); - } - }; - - /// Copy ctor - eoESChrom( const eoESChrom& _eoes): eoVector( _eoes ) {}; - - /// Assignment operator - const eoESChrom& operator =( const eoESChrom & _eoes ) { - if ( this != &_eoes ){ - eoVector::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 // For vector<> +#include +#include +#include // for ostream + +// EO includes +#include + +/**@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 +class eoESChrom: public eoVector { +public: + /// Basic ctor + eoESChrom( ):eoVector() {}; + + /** 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& _rnd, eoRnd& _rndS ) + : eoVector( _size ){ + for ( iterator i = begin(); i != end(); i ++ ) { + i->val = _rnd(); + i->sigma = _rndS(); + } + }; + + /// Copy ctor + eoESChrom( const eoESChrom& _eoes): eoVector( _eoes ) {}; + + /// Assignment operator + const eoESChrom& operator =( const eoESChrom & _eoes ) { + if ( this != &_eoes ){ + eoVector::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 + diff --git a/eo/src/eoESFullChrom.h b/eo/src/eoESFullChrom.h index 5b206c73..29c56656 100644 --- a/eo/src/eoESFullChrom.h +++ b/eo/src/eoESFullChrom.h @@ -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 // For vector<> -#include -#include -#include // for ostream - -// EO includes -#include -#include -/**@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 -class eoESFullChrom : public eoVector { - 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(_num_genes), - // ObjVar( _num_genes ), now an eoVector - StdDev( _num_sigma ), - CorCff( _num_correl ), - verbose( _verbose ), - ObjMin( _ObjMin ), - ObjMax(_ObjMax ), - StdDevInit( _StdDevInit ) {} - - /// copy constructor - eoESFullChrom( const eoESFullChrom& _eo ): - eoVector ( _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 // For vector<> +#include +#include +#include // for ostream + +// EO includes +#include +#include +/**@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 +class eoESFullChrom : public eoVector { + 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(_num_genes), + // ObjVar( _num_genes ), now an eoVector + StdDev( _num_sigma ), + CorCff( _num_correl ), + verbose( _verbose ), + ObjMin( _ObjMin ), + ObjMax(_ObjMax ), + StdDevInit( _StdDevInit ) {} + + /// copy constructor + eoESFullChrom( const eoESFullChrom& _eo ): + eoVector ( _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::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( _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( _s, " ") ); - if (CorCff.size()) { - _s << "\n\t"; - copy( CorCff.begin(), CorCff.end(), ostream_iterator( _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 ObjVar; /* object variable vector */ -// or shoudl the class be subclass of EOVector ??? - - vector StdDev; /* standard deviation vector */ - vector 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::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( _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( _s, " ") ); + if (CorCff.size()) { + _s << "\n\t"; + copy( CorCff.begin(), CorCff.end(), ostream_iterator( _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 ObjVar; /* object variable vector */ +// or shoudl the class be subclass of EOVector ??? + + vector StdDev; /* standard deviation vector */ + vector 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 + + diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index 2b5fa4f4..ecd95c8e 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -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 // eoPop -#include - -/** 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 eoEasyEA: public eoAlgo -{ - public: - /// Constructor. - eoEasyEA(eoBinPopOp& _select, - eoMonPopOp& _transform, - eoBinPopOp& _replace, - eoEvalFunc& _evaluator, - eoTerm& _terminator) - :step(_select, _transform, _replace, _evaluator), - terminator( _terminator){}; - - /// Constructor from an already created generation - eoEasyEA(eoGeneration& _gen, - eoTerm& _terminator): - step(_gen), - terminator( _terminator){}; - - /// Apply one generation of evolution to the population. - virtual void operator()(eoPop& 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 // eoPop +#include + +/** 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 eoEasyEA: public eoAlgo +{ + public: + /// Constructor. + eoEasyEA(eoBinPopOp& _select, + eoMonPopOp& _transform, + eoBinPopOp& _replace, + eoEvalFunc& _evaluator, + eoTerm& _terminator) + :step(_select, _transform, _replace, _evaluator), + terminator( _terminator){}; + + /// Constructor from an already created generation + eoEasyEA(eoGeneration& _gen, + eoTerm& _terminator): + step(_gen), + terminator( _terminator){}; + + /// Apply one generation of evolution to the population. + virtual void operator()(eoPop& 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 step; - eoTerm& terminator; -}; - -//----------------------------------------------------------------------------- - -#endif eoEasyEA_h + } + + /// Class name. + string className() const { return "eoEasyEA"; } + + private: + eoGeneration step; + eoTerm& terminator; +}; + +//----------------------------------------------------------------------------- + +#endif eoEasyEA_h + diff --git a/eo/src/eoEvalFuncPtr.h b/eo/src/eoEvalFuncPtr.h index d6d387d6..04cd6de8 100644 --- a/eo/src/eoEvalFuncPtr.h +++ b/eo/src/eoEvalFuncPtr.h @@ -1,59 +1,60 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - ------------------------------------------------------------------------------ - eoEvalFuncPtr.h - Converts a classical C fitness evaluation function into a fitness - evaluation object - - (c) GeNeura Team, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef EOEVALFUNCPTR_H -#define EOEVALFUNCPTR_H - -#include - -/** EOEvalFuncPtr: This class - * takes an existing function pointer and converts it into a evaluation - * function class. That way, old style C or C++ functions can be adapted to EO - * function classes. - */ -template< class EOT > -struct eoEvalFuncPtr: public eoEvalFunc { - - /** Applies the function to the chromosome and sets the fitness of the - Chrom. Thus, the evaluation function need not be worried about that. - @param _eval pointer to the evaluation function, takes a EOT as an - argument and returns the fitness - @return the evaluated fitness for that object. - */ - eoEvalFuncPtr( EOFitT (* _eval)( const EOT& ) ) - : eoEvalFunc(), evalFunc( _eval ) {}; - - /// Effectively applies the evaluation function to an EO - virtual void operator() ( EOT & _eo ) const { - _eo.fitness((*evalFunc)( _eo )); - }; - - private: - EOFitT (* evalFunc )( const EOT& ); -}; - -#endif +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +----------------------------------------------------------------------------- + eoEvalFuncPtr.h + Converts a classical C fitness evaluation function into a fitness + evaluation object + + (c) GeNeura Team, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOEVALFUNCPTR_H +#define EOEVALFUNCPTR_H + +#include + +/** EOEvalFuncPtr: This class + * takes an existing function pointer and converts it into a evaluation + * function class. That way, old style C or C++ functions can be adapted to EO + * function classes. + */ +template< class EOT > +struct eoEvalFuncPtr: public eoEvalFunc { + + /** Applies the function to the chromosome and sets the fitness of the + Chrom. Thus, the evaluation function need not be worried about that. + @param _eval pointer to the evaluation function, takes a EOT as an + argument and returns the fitness + @return the evaluated fitness for that object. + */ + eoEvalFuncPtr( EOFitT (* _eval)( const EOT& ) ) + : eoEvalFunc(), evalFunc( _eval ) {}; + + /// Effectively applies the evaluation function to an EO + virtual void operator() ( EOT & _eo ) const { + _eo.fitness((*evalFunc)( _eo )); + }; + + private: + EOFitT (* evalFunc )( const EOT& ); +}; + +#endif + diff --git a/eo/src/eoException.h b/eo/src/eoException.h index e135757e..2e3ae02a 100644 --- a/eo/src/eoException.h +++ b/eo/src/eoException.h @@ -1,69 +1,69 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - ------------------------------------------------------------------------------ - eoException.h - Exceptions that are possibly thrown at initialization and such should be - defined here - - (c) GeNeura Team, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef eoException_h -#define eoException_h - -#include - -#include "eoObject.h" - -struct eoException -{ - eoException() {} - eoException(const eoObject& caller) : who_caught_it(caller.className()) {} - - std::string who(void) const { return who_caught_it; } - virtual std::string what(void) const{ return "";} - -private : - std::string who_caught_it; -}; - -struct eoFitnessException : public eoException -{ - eoFitnessException() : eoException() {} - eoFitnessException(const eoObject& caller) : eoException(caller) {} -}; - -struct eoNegativeFitnessException : public eoFitnessException -{ - eoNegativeFitnessException() : eoFitnessException() {} - eoNegativeFitnessException(const eoObject& caller) : eoFitnessException(caller) {} - - std::string what(void) const { return "negative fitness encountered"; } -}; - -struct eoMinimizingFitnessException : public eoFitnessException -{ - eoMinimizingFitnessException() : eoFitnessException() {} - eoMinimizingFitnessException(const eoObject& caller) : eoFitnessException(caller) {} - - std::string what(void) const { return "smaller fitness is better fitness, which is quite inappropriate here"; } -}; - -#endif \ No newline at end of file +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +----------------------------------------------------------------------------- + eoException.h + Exceptions that are possibly thrown at initialization and such should be + defined here. + + (c) GeNeura Team, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoException_h +#define eoException_h + +#include + +#include "eoObject.h" + +struct eoException +{ + eoException() {} + eoException(const eoObject& caller) : who_caught_it(caller.className()) {} + + std::string who(void) const { return who_caught_it; } + virtual std::string what(void) const{ return "";} + +private : + std::string who_caught_it; +}; + +struct eoFitnessException : public eoException +{ + eoFitnessException() : eoException() {} + eoFitnessException(const eoObject& caller) : eoException(caller) {} +}; + +struct eoNegativeFitnessException : public eoFitnessException +{ + eoNegativeFitnessException() : eoFitnessException() {} + eoNegativeFitnessException(const eoObject& caller) : eoFitnessException(caller) {} + + std::string what(void) const { return "negative fitness encountered"; } +}; + +struct eoMinimizingFitnessException : public eoFitnessException +{ + eoMinimizingFitnessException() : eoFitnessException() {} + eoMinimizingFitnessException(const eoObject& caller) : eoFitnessException(caller) {} + + std::string what(void) const { return "smaller fitness is better fitness, which is quite inappropriate here"; } +}; + +#endif diff --git a/eo/src/eoFitTerm.h b/eo/src/eoFitTerm.h index 4181015f..76f696d8 100644 --- a/eo/src/eoFitTerm.h +++ b/eo/src/eoFitTerm.h @@ -1,64 +1,65 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoGenTerm.h -// (c) GeNeura Team, 1999 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EOFITTERM_H -#define _EOFITTERM_H - -#include - - -/** Fitness termination: terminates after a the difference between the -fitness of the best individual and a maximum fitness to achieve is less -than certain number called epsilon., i.e., |maximum-fitness| -class eoFitTerm: public eoTerm { -public: - - /// Ctors/dtors - eoFitTerm( const float _maximum, const float _epsilon ) - : eoTerm (), maximum( _maximum ), epsilon(_epsilon){}; - - /// Copy ctor - eoFitTerm( const eoFitTerm& _t ) - : eoTerm ( _t ), maximum( _t.maximum ), - epsilon(_t.epsilon){}; - - /// - virtual ~eoFitTerm() {}; - - /** Returns false when a certain number of generations is - * reached */ - virtual bool operator() ( const eoPop& _vEO ) { - float bestFitness=_vEO[0].fitness(); - float dif=bestFitness-maximum; - dif=(dif<0)?-dif:dif; - return (dif>epsilon ) || (bestFitness > maximum); - } - -private: - float maximum, epsilon; -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenTerm.h +// (c) GeNeura Team, 1999 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOFITTERM_H +#define _EOFITTERM_H + +#include + + +/** Fitness termination: terminates after a the difference between the +fitness of the best individual and a maximum fitness to achieve is less +than certain number called epsilon., i.e., |maximum-fitness| +class eoFitTerm: public eoTerm { +public: + + /// Ctors/dtors + eoFitTerm( const float _maximum, const float _epsilon ) + : eoTerm (), maximum( _maximum ), epsilon(_epsilon){}; + + /// Copy ctor + eoFitTerm( const eoFitTerm& _t ) + : eoTerm ( _t ), maximum( _t.maximum ), + epsilon(_t.epsilon){}; + + /// + virtual ~eoFitTerm() {}; + + /** Returns false when a certain number of generations is + * reached */ + virtual bool operator() ( const eoPop& _vEO ) { + float bestFitness=_vEO[0].fitness(); + float dif=bestFitness-maximum; + dif=(dif<0)?-dif:dif; + return (dif>epsilon ) || (bestFitness > maximum); + } + +private: + float maximum, epsilon; +}; + +#endif + diff --git a/eo/src/eoFitness.h b/eo/src/eoFitness.h index 8505c34f..ea514ae6 100644 --- a/eo/src/eoFitness.h +++ b/eo/src/eoFitness.h @@ -1,54 +1,55 @@ -// eoFitness.h -//----------------------------------------------------------------------------- -// eoFitness.cpp -// (c) GeNeura Team 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef EOFITNESS_H -#define EOFITNESS_H - -//----------------------------------------------------------------------------- - -class eoFitness: public eoPersistent -{ - public: - virtual operator float() const = 0; - - virtual bool operator<(const eoFitness& other) const = 0; - - virtual bool operator>(const eoFitness& other) const - { - return !(*this < other || *this == other); - } - - virtual bool operator==(const eoFitness& other) const - { - return !(other < *this || *this < other); - } - - virtual bool operator!=(const eoFitness& other) const - { - return other < *this || *this < other; - } -}; - -//----------------------------------------------------------------------------- - -#endif EOFITNESS_H +// eoFitness.h +//----------------------------------------------------------------------------- +// eoFitness.cpp +// (c) GeNeura Team 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOFITNESS_H +#define EOFITNESS_H + +//----------------------------------------------------------------------------- + +class eoFitness: public eoPersistent +{ + public: + virtual operator float() const = 0; + + virtual bool operator<(const eoFitness& other) const = 0; + + virtual bool operator>(const eoFitness& other) const + { + return !(*this < other || *this == other); + } + + virtual bool operator==(const eoFitness& other) const + { + return !(other < *this || *this < other); + } + + virtual bool operator!=(const eoFitness& other) const + { + return other < *this || *this < other; + } +}; + +//----------------------------------------------------------------------------- + +#endif EOFITNESS_H + diff --git a/eo/src/eoGOpBreeder.h b/eo/src/eoGOpBreeder.h index f690b591..ecdfd865 100644 --- a/eo/src/eoGOpBreeder.h +++ b/eo/src/eoGOpBreeder.h @@ -1,58 +1,59 @@ -//----------------------------------------------------------------------------- -// eoBreeder.h -//----------------------------------------------------------------------------- - -#ifndef eoGopBreeder_h -#define eoGopBreeder_h - -//----------------------------------------------------------------------------- - -/***************************************************************************** - * eoBreeder: transforms a population using genetic operators. * - * For every operator there is a rated to be applyed. * - *****************************************************************************/ - -#include "eoPopOps.h" -#include "eoGOpSelector.h" -#include "eoIndiSelector.h" -#include "eoBackInserter.h" - -template -class eoGOpBreeder: public eoMonPopOp -{ - public: - /// Default constructor. - eoGOpBreeder( eoGOpSelector& _opSel, - eoPopIndiSelector& _selector) - : opSel( _opSel ), selector(_selector) - {} - - /// Destructor. - virtual ~eoGOpBreeder() {} - - /** - * Enlarges the population. - * @param pop The population to be transformed. - */ - void operator()(eoPop& _pop) - { - int size = _pop.size(); - - for (unsigned i = 0; i < size; i++) - { // and the one liner - opSel.selectOp()(selector(_pop,size, i), inserter(_pop)); - } - } - - /// The class name. - string classname() const { return "eoGOpBreeder"; } - - private: - eoGOpSelector& opSel; - eoPopIndiSelector& selector; - - // the inserter can be local as there's no point in changing it from the outside - eoBackInserter inserter; -}; - -#endif eoBreeder_h +//----------------------------------------------------------------------------- +// eoBreeder.h +//----------------------------------------------------------------------------- + +#ifndef eoGopBreeder_h +#define eoGopBreeder_h + +//----------------------------------------------------------------------------- + +/***************************************************************************** + * eoBreeder: transforms a population using genetic operators. * + * For every operator there is a rated to be applyed. * + *****************************************************************************/ + +#include "eoPopOps.h" +#include "eoGOpSelector.h" +#include "eoIndiSelector.h" +#include "eoBackInserter.h" + +template +class eoGOpBreeder: public eoMonPopOp +{ + public: + /// Default constructor. + eoGOpBreeder( eoGOpSelector& _opSel, + eoPopIndiSelector& _selector) + : opSel( _opSel ), selector(_selector) + {} + + /// Destructor. + virtual ~eoGOpBreeder() {} + + /** + * Enlarges the population. + * @param pop The population to be transformed. + */ + void operator()(eoPop& _pop) + { + int size = _pop.size(); + + for (unsigned i = 0; i < size; i++) + { // and the one liner + opSel.selectOp()(selector(_pop,size, i), inserter(_pop)); + } + } + + /// The class name. + string classname() const { return "eoGOpBreeder"; } + + private: + eoGOpSelector& opSel; + eoPopIndiSelector& selector; + + // the inserter can be local as there's no point in changing it from the outside + eoBackInserter inserter; +}; + +#endif eoBreeder_h + diff --git a/eo/src/eoGOpSelector.h b/eo/src/eoGOpSelector.h index 2370d72f..030380ac 100644 --- a/eo/src/eoGOpSelector.h +++ b/eo/src/eoGOpSelector.h @@ -1,173 +1,174 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoGOpSelector.h - Base class for generalized (n-inputs, n-outputs) operator selectors. - Includes code and variables that contain operators and rates. - Also included eoProportionalGOpSelector and eoSequentialGOpSelector, that offer - a few concrete implementations. - - (c) Maarten Keijzer, GeNeura Team 1998, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es -*/ - -#ifndef eoGOpSelector_h -#define eoGOpSelector_h - -//----------------------------------------------------------------------------- - -#include -#include "eoOpSelector.h" -#include "eoWrappedOps.h" // for eoCombinedOp -#include "eoRNG.h" - -using namespace std; - -/** Base class for alternative selectors, which use the generalized operator - interface. eoGOpBreeders expects this class */ -template -class eoGOpSelector: public eoOpSelector, public vector*> -{ -public: - - typedef eoOpSelector::ID ID; - - /// Dtor - virtual ~eoGOpSelector() { - for ( list< eoGeneralOp* >::iterator i= ownOpList.begin(); - i != ownOpList.end(); i++ ) { - delete *i; - } - } - - /// Add any kind of operator to the operator mix, with an argument - virtual ID addOp( eoOp& _op, float _arg ); - // implementation can be found below - - /** Retrieve the operator using its integer handle - @param _id The id number. Should be a valid id, or an exception - will be thrown - @return a reference of the operator corresponding to that id. - */ - virtual const eoOp& getOp( ID _id ) - { - return *operator[](_id); - } - - /// - virtual void deleteOp( ID _id ); - // implemented below - - /// - virtual eoOp* Op() - { - return &selectOp(); - } - - /// - virtual eoGeneralOp& selectOp() = 0; - - /// - virtual string className() const { return "eoGOpSelector"; }; - - /// - void printOn(ostream& _os) const {} - // _os << className().c_str() << endl; - // for ( unsigned i=0; i!= rates.size(); i++ ) { - // _os << *(operator[](i)) << "\t" << rates[i] << endl; - // } - //} - - - const vector& getRates(void) const { return rates; } - -private : - vector rates; - list< eoGeneralOp* > ownOpList; -}; - -/* Implementation of longish functions defined above */ - -template -inline eoOpSelector::ID eoGOpSelector::addOp( eoOp& _op, float _arg ) -{ - - eoGeneralOp* op; - - if (_op.getType() == eoOp::general) - { - op = static_cast*>(&_op); - } - else - { - // if it's not a general op, it's a "old" op; create a wrapped op from it - // and keep it on a list to delete them afterwards - // will use auto_ptr when they're readily available - - switch(_op.getType()) - { - case eoOp::unary : - op= new eoWrappedMonOp(static_cast&>(_op)); - break; - case eoOp::binary : - op = new eoWrappedBinOp(static_cast&>(_op)); - case eoOp::quadratic : - op = new eoWrappedQuadraticOp(static_cast&>(_op)); - break; - } - ownOpList.push_back( op ); - } - - // Now 'op' is a general operator, either because '_op' was one or - // because we wrapped it in an appropriate wrapper in the code above. - - iterator result = find(begin(), end(), (eoGeneralOp*) 0); // search for nullpointer - - if (result == end()) - { - push_back(op); - rates.push_back(_arg); - return size(); - } - // else - - *result = op; - ID id = result - begin(); - rates[id] = _arg; - return id; -} - -template -inline void eoGOpSelector::deleteOp( ID _id ) -{ - eoGeneralOp* op = operator[](_id); - - operator[](_id) = 0; - rates[_id] = 0.0; - - // check oplist and clear it there too. - - list< eoGeneralOp* >::iterator it = find(ownOpList.begin(), ownOpList.end(), op); - - if(it != ownOpList.end()) - { - ownOpList.erase(it); - } -} - -#endif eoGOpSelector_h +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoGOpSelector.h + Base class for generalized (n-inputs, n-outputs) operator selectors. + Includes code and variables that contain operators and rates. + Also included eoProportionalGOpSelector and eoSequentialGOpSelector, that offer + a few concrete implementations. + + (c) Maarten Keijzer, GeNeura Team 1998, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es +*/ + +#ifndef eoGOpSelector_h +#define eoGOpSelector_h + +//----------------------------------------------------------------------------- + +#include +#include "eoOpSelector.h" +#include "eoWrappedOps.h" // for eoCombinedOp +#include "eoRNG.h" + +using namespace std; + +/** Base class for alternative selectors, which use the generalized operator + interface. eoGOpBreeders expects this class */ +template +class eoGOpSelector: public eoOpSelector, public vector*> +{ +public: + + typedef eoOpSelector::ID ID; + + /// Dtor + virtual ~eoGOpSelector() { + for ( list< eoGeneralOp* >::iterator i= ownOpList.begin(); + i != ownOpList.end(); i++ ) { + delete *i; + } + } + + /// Add any kind of operator to the operator mix, with an argument + virtual ID addOp( eoOp& _op, float _arg ); + // implementation can be found below + + /** Retrieve the operator using its integer handle + @param _id The id number. Should be a valid id, or an exception + will be thrown + @return a reference of the operator corresponding to that id. + */ + virtual const eoOp& getOp( ID _id ) + { + return *operator[](_id); + } + + /// + virtual void deleteOp( ID _id ); + // implemented below + + /// + virtual eoOp* Op() + { + return &selectOp(); + } + + /// + virtual eoGeneralOp& selectOp() = 0; + + /// + virtual string className() const { return "eoGOpSelector"; }; + + /// + void printOn(ostream& _os) const {} + // _os << className().c_str() << endl; + // for ( unsigned i=0; i!= rates.size(); i++ ) { + // _os << *(operator[](i)) << "\t" << rates[i] << endl; + // } + //} + + + const vector& getRates(void) const { return rates; } + +private : + vector rates; + list< eoGeneralOp* > ownOpList; +}; + +/* Implementation of longish functions defined above */ + +template +inline eoOpSelector::ID eoGOpSelector::addOp( eoOp& _op, float _arg ) +{ + + eoGeneralOp* op; + + if (_op.getType() == eoOp::general) + { + op = static_cast*>(&_op); + } + else + { + // if it's not a general op, it's a "old" op; create a wrapped op from it + // and keep it on a list to delete them afterwards + // will use auto_ptr when they're readily available + + switch(_op.getType()) + { + case eoOp::unary : + op= new eoWrappedMonOp(static_cast&>(_op)); + break; + case eoOp::binary : + op = new eoWrappedBinOp(static_cast&>(_op)); + case eoOp::quadratic : + op = new eoWrappedQuadraticOp(static_cast&>(_op)); + break; + } + ownOpList.push_back( op ); + } + + // Now 'op' is a general operator, either because '_op' was one or + // because we wrapped it in an appropriate wrapper in the code above. + + iterator result = find(begin(), end(), (eoGeneralOp*) 0); // search for nullpointer + + if (result == end()) + { + push_back(op); + rates.push_back(_arg); + return size(); + } + // else + + *result = op; + ID id = result - begin(); + rates[id] = _arg; + return id; +} + +template +inline void eoGOpSelector::deleteOp( ID _id ) +{ + eoGeneralOp* op = operator[](_id); + + operator[](_id) = 0; + rates[_id] = 0.0; + + // check oplist and clear it there too. + + list< eoGeneralOp* >::iterator it = find(ownOpList.begin(), ownOpList.end(), op); + + if(it != ownOpList.end()) + { + ownOpList.erase(it); + } +} + +#endif eoGOpSelector_h + diff --git a/eo/src/eoGenTerm.h b/eo/src/eoGenTerm.h index 3e6b0aa5..b6fc60f5 100644 --- a/eo/src/eoGenTerm.h +++ b/eo/src/eoGenTerm.h @@ -1,82 +1,83 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoGenTerm.h -// (c) GeNeura Team, 1999 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EOGENTERM_H -#define _EOGENTERM_H - -#include - -/** Generational termination: terminates after a number of generations -*/ -template< class EOT> -class eoGenTerm: public eoTerm { -public: - - /// Ctors/dtors - eoGenTerm( unsigned _totalGens) - : eoTerm (), repTotalGenerations( _totalGens ), - thisGeneration(0){}; - - /// Copy Ctor - eoGenTerm( const eoGenTerm& _t) - : eoTerm ( _t ), repTotalGenerations( _t.repTotalGenerations ), - thisGeneration(0){}; - - /// Assignment Operator - const eoGenTerm& operator = ( const eoGenTerm& _t) { - if ( &_t != this ) { - repTotalGenerations = _t.repTotalGenerations; - thisGeneration = 0; - } - return *this; - } - - /// Dtor - virtual ~eoGenTerm() {}; - - /** Returns false when a certain number of generations is - * reached */ - virtual bool operator() ( const eoPop& _vEO ) { - thisGeneration++; - // cout << " [" << thisGeneration << "] "; - return (thisGeneration < repTotalGenerations) ; // for the postincrement - } - - /** Sets the number of generations to reach - and sets the current generation to 0 (the begin)*/ - virtual void totalGenerations( unsigned _tg ) { - repTotalGenerations = _tg; - // thisGeneration = 0; - }; - - /** Returns the number of generations to reach*/ - virtual unsigned totalGenerations( ) { - return repTotalGenerations; - }; - -private: - unsigned repTotalGenerations, thisGeneration; -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenTerm.h +// (c) GeNeura Team, 1999 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOGENTERM_H +#define _EOGENTERM_H + +#include + +/** Generational termination: terminates after a number of generations +*/ +template< class EOT> +class eoGenTerm: public eoTerm { +public: + + /// Ctors/dtors + eoGenTerm( unsigned _totalGens) + : eoTerm (), repTotalGenerations( _totalGens ), + thisGeneration(0){}; + + /// Copy Ctor + eoGenTerm( const eoGenTerm& _t) + : eoTerm ( _t ), repTotalGenerations( _t.repTotalGenerations ), + thisGeneration(0){}; + + /// Assignment Operator + const eoGenTerm& operator = ( const eoGenTerm& _t) { + if ( &_t != this ) { + repTotalGenerations = _t.repTotalGenerations; + thisGeneration = 0; + } + return *this; + } + + /// Dtor + virtual ~eoGenTerm() {}; + + /** Returns false when a certain number of generations is + * reached */ + virtual bool operator() ( const eoPop& _vEO ) { + thisGeneration++; + // cout << " [" << thisGeneration << "] "; + return (thisGeneration < repTotalGenerations) ; // for the postincrement + } + + /** Sets the number of generations to reach + and sets the current generation to 0 (the begin)*/ + virtual void totalGenerations( unsigned _tg ) { + repTotalGenerations = _tg; + // thisGeneration = 0; + }; + + /** Returns the number of generations to reach*/ + virtual unsigned totalGenerations( ) { + return repTotalGenerations; + }; + +private: + unsigned repTotalGenerations, thisGeneration; +}; + +#endif + diff --git a/eo/src/eoID.h b/eo/src/eoID.h index ed8ceecd..f7d65ec7 100644 --- a/eo/src/eoID.h +++ b/eo/src/eoID.h @@ -1,109 +1,110 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoID.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef EOID_H -#define EOID_H - -//----------------------------------------------------------------------------- - -#include // istream, ostream -#include // for string - -using namespace std; - -//----------------------------------------------------------------------------- -// eoID -//----------------------------------------------------------------------------- - -/** eoID is a template class that adds an ID to an object.\\ -Requisites for template instantiation are that the object must admit a default ctor -and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className, -printOn, readFrom, that is why we don´t subclass eoObject to avoid multiple inheritance.\\ -IDs can be used to count objects of a a kind, or track them, or whatever. -@see eoObject -*/ -template -class eoID: public Object -{ - public: - /// Main ctor from an already built Object. - eoID( const Object& _o): Object( _o ), thisID(globalID++) {}; - - /// Copy constructor. - eoID( const eoID& _id): Object( _id ), thisID(globalID++ ) {}; - - /// Virtual dtor. They are needed in virtual class hierarchies - virtual ~eoID() {}; - - - ///returns the age of the object - unsigned long ID() const {return thisID;} - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eo1d - */ - //@{ - /** Return the class id. This should be redefined in each class; but - it's got code as an example of implementation. Only "leaf" classes - can be non-virtual. - */ - virtual string className() const { return string("[eoID]")+Object::className(); }; - - /** - * Read object. - * @param _is A istream. - * @throw runtime_exception If a valid object can't be read. - */ - virtual void readFrom(istream& _is) { - Object::readFrom( _is ); - _is >> thisID; - } - - - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. - */ - virtual void printOn(ostream& _os) const{ - Object::printOn( _os ); - _os << thisID; - } -//@} - - private: - - /** Default Constructor. \\ - It´s private so that it is not used anywhere; the right way of using this object - is to create an Object and passing it to an aged by means of the copy ctor; that way - it´s turned into an Aged object*/ - eoID(): Object(), thisID( globalID++ ) {}; - - unsigned long thisID; - static unsigned long globalID; -}; - -template< class Object> -unsigned long eoID< Object >::globalID = 0; - -#endif EOID_H +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoID.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOID_H +#define EOID_H + +//----------------------------------------------------------------------------- + +#include // istream, ostream +#include // for string + +using namespace std; + +//----------------------------------------------------------------------------- +// eoID +//----------------------------------------------------------------------------- + +/** eoID is a template class that adds an ID to an object.\\ +Requisites for template instantiation are that the object must admit a default ctor +and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className, +printOn, readFrom, that is why we don´t subclass eoObject to avoid multiple inheritance.\\ +IDs can be used to count objects of a a kind, or track them, or whatever. +@see eoObject +*/ +template +class eoID: public Object +{ + public: + /// Main ctor from an already built Object. + eoID( const Object& _o): Object( _o ), thisID(globalID++) {}; + + /// Copy constructor. + eoID( const eoID& _id): Object( _id ), thisID(globalID++ ) {}; + + /// Virtual dtor. They are needed in virtual class hierarchies + virtual ~eoID() {}; + + + ///returns the age of the object + unsigned long ID() const {return thisID;} + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eo1d + */ + //@{ + /** Return the class id. This should be redefined in each class; but + it's got code as an example of implementation. Only "leaf" classes + can be non-virtual. + */ + virtual string className() const { return string("[eoID]")+Object::className(); }; + + /** + * Read object. + * @param _is A istream. + * @throw runtime_exception If a valid object can't be read. + */ + virtual void readFrom(istream& _is) { + Object::readFrom( _is ); + _is >> thisID; + } + + + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A ostream. + */ + virtual void printOn(ostream& _os) const{ + Object::printOn( _os ); + _os << thisID; + } +//@} + + private: + + /** Default Constructor. \\ + It´s private so that it is not used anywhere; the right way of using this object + is to create an Object and passing it to an aged by means of the copy ctor; that way + it´s turned into an Aged object*/ + eoID(): Object(), thisID( globalID++ ) {}; + + unsigned long thisID; + static unsigned long globalID; +}; + +template< class Object> +unsigned long eoID< Object >::globalID = 0; + +#endif EOID_H + diff --git a/eo/src/eoIndiSelector.h b/eo/src/eoIndiSelector.h index c534404c..69803d2b 100644 --- a/eo/src/eoIndiSelector.h +++ b/eo/src/eoIndiSelector.h @@ -1,134 +1,134 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoIndiSelector.h - Abstract selection operator, which is used by the eoGeneralOps - to obtain individuals from a source population. It also gives a - direct descended eoPopIndiSelector that can be used to - initialize objects with an eoPop. For most uses use eoPopIndividualSelector - rather than eoIndividualSelector to derive from. - - (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ - -#ifndef eoIndiSelector_h -#define eoIndiSelector_h - -/** - * eoIndividualSelector: This class defines the interface -*/ -template -class eoIndiSelector -{ -public : - - eoIndiSelector() {} - - virtual ~eoIndiSelector(void) {} - - virtual size_t size(void) const = 0; - virtual const EOT& operator[](size_t) const = 0; - - virtual const EOT& select(void) = 0; - - virtual vector select(size_t _how_many) - { // default implementation just calls select a couple of times - // this can be overridden in favour of a more efficient implementation - vector result(_how_many); - - for (int i = 0; i < _how_many; ++i) - { - result[i] = &select(); - } - - return result; - } -}; - -/** - * eoPopIndiSelector: Intermediate class for dispensing populations - various useful things can be done with this class: - you can specify how many of the population can ever be dispensed to the - operators, but you can also specify a preference to the first guy being - dispensed. This is useful if you want to perform the operator on a specific - individual. -*/ -template -class eoPopIndiSelector : public eoIndiSelector -{ - public : - eoPopIndiSelector(void) : pop(0), firstChoice(-1), last(0), eoIndiSelector() {} - - virtual ~eoPopIndiSelector(void) {} - - struct eoUnitializedException{}; - - /** Initialization function - */ - eoPopIndiSelector& operator()(const eoPop& _pop, int _end = -1, int _myGuy = -1) - { - pop = &_pop; - last = _end; - - if (last < 0 || last > pop->size()) - { - last = pop->size(); - } - - firstChoice = _myGuy; - return *this; - } - - size_t size(void) const { valid(); return last; } - const EOT& operator[](size_t _i) const { valid(); return pop->operator[](_i); } - - eoPop::const_iterator begin(void) const { valid(); return pop->begin(); } - eoPop::const_iterator end(void) const { valid(); return pop->end(); } - - - /// select does the work. Note that it is not virtual. It calls do_select that needs to be implemented by the derived classes - const EOT& select(void) - { - valid(); - if (firstChoice < 0 || firstChoice >= size()) - { - return do_select(); // let the child figure out what to do - } - - const EOT& result = pop->operator[](firstChoice); - firstChoice = -1; - return result; - } - - virtual const EOT& do_select(void) = 0; - - private : - - void valid(void) const - { - if (pop == 0) - throw eoUnitializedException(); - } - - const eoPop* pop; // need a pointer as this the pop argument can be re-instated - int last; - int firstChoice; -}; - -#endif \ No newline at end of file +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoIndiSelector.h + Abstract selection operator, which is used by the eoGeneralOps + to obtain individuals from a source population. It also gives a + direct descended eoPopIndiSelector that can be used to + initialize objects with an eoPop. For most uses use eoPopIndividualSelector + rather than eoIndividualSelector to derive from. + + (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef eoIndiSelector_h +#define eoIndiSelector_h + +/** + * eoIndividualSelector: This class defines the interface +*/ +template +class eoIndiSelector +{ +public : + + eoIndiSelector() {} + + virtual ~eoIndiSelector(void) {} + + virtual size_t size(void) const = 0; + virtual const EOT& operator[](size_t) const = 0; + + virtual const EOT& select(void) = 0; + + virtual vector select(size_t _how_many) + { // default implementation just calls select a couple of times + // this can be overridden in favour of a more efficient implementation + vector result(_how_many); + + for (int i = 0; i < _how_many; ++i) + { + result[i] = &select(); + } + + return result; + } +}; + +/** + * eoPopIndiSelector: Intermediate class for dispensing populations + various useful things can be done with this class: + you can specify how many of the population can ever be dispensed to the + operators, but you can also specify a preference to the first guy being + dispensed. This is useful if you want to perform the operator on a specific + individual. +*/ +template +class eoPopIndiSelector : public eoIndiSelector +{ + public : + eoPopIndiSelector(void) : pop(0), firstChoice(-1), last(0), eoIndiSelector() {} + + virtual ~eoPopIndiSelector(void) {} + + struct eoUnitializedException{}; + + /** Initialization function + */ + eoPopIndiSelector& operator()(const eoPop& _pop, int _end = -1, int _myGuy = -1) + { + pop = &_pop; + last = _end; + + if (last < 0 || last > pop->size()) + { + last = pop->size(); + } + + firstChoice = _myGuy; + return *this; + } + + size_t size(void) const { valid(); return last; } + const EOT& operator[](size_t _i) const { valid(); return pop->operator[](_i); } + + eoPop::const_iterator begin(void) const { valid(); return pop->begin(); } + eoPop::const_iterator end(void) const { valid(); return pop->end(); } + + + /// select does the work. Note that it is not virtual. It calls do_select that needs to be implemented by the derived classes + const EOT& select(void) + { + valid(); + if (firstChoice < 0 || firstChoice >= size()) + { + return do_select(); // let the child figure out what to do + } + + const EOT& result = pop->operator[](firstChoice); + firstChoice = -1; + return result; + } + + virtual const EOT& do_select(void) = 0; + + private : + + void valid(void) const + { + if (pop == 0) + throw eoUnitializedException(); + } + + const eoPop* pop; // need a pointer as this the pop argument can be re-instated + int last; + int firstChoice; +}; + +#endif diff --git a/eo/src/eoInserter.h b/eo/src/eoInserter.h index eb9eb3c6..44ec6885 100644 --- a/eo/src/eoInserter.h +++ b/eo/src/eoInserter.h @@ -1,92 +1,93 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoInserter.h - Abstract population insertion operator, which is used by the eoGeneralOps - to insert the results in the (intermediate) population. It also contains - a direct descended eoPopInserter that defines a convenient inbetween class - for working with eoPop. The user will most likely derive from eoPopInserter - rather than eoInserter. - - (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ - -#ifndef eoInserter_h -#define eoInserter_h - -#include "eoPop.h" -/** - * eoInserter: Interface class that enables an operator to insert - new individuals into the (intermediate) population. -*/ -template -class eoInserter : public eoObject -{ - public : - virtual ~eoInserter() {} - - struct eoInserterException{}; - - virtual void insert(const EOT&) = 0; // can throw an eoInserterException -}; - -/** - * eoPopInserter: In-between class that defines an initialization - * of the eoIndividualInserter. -*/ -template -class eoPopInserter : public eoInserter -{ - public : - - eoPopInserter(void) : thePop(0), eoInserter() {} - - /// Binds the population to this class. This is an initialization routine used by breeders - eoInserter& operator()(eoPop& _pop) - { - thePop = &_pop; - return *this; - } - - protected : - - eoPop& pop(void) const { valid(); return *thePop; } - - private : - - void valid(void) const - { - if (thePop == 0) - throw eoInserterException(); - } - - // Need a pointer as the inserter should be able to bind to different populations. - // This is caused by the 'one template parameter only' convention in EO. - - eoPop* thePop; - - // If eoGOpBreeder could be templatized over the inserter and the selector, - // the pop could be a ref as this class could be created every time it is applied - // and subsequently would get the population through the constructor - -}; - - - -#endif +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoInserter.h + Abstract population insertion operator, which is used by the eoGeneralOps + to insert the results in the (intermediate) population. It also contains + a direct descended eoPopInserter that defines a convenient inbetween class + for working with eoPop. The user will most likely derive from eoPopInserter + rather than eoInserter. + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef eoInserter_h +#define eoInserter_h + +#include "eoPop.h" +/** + * eoInserter: Interface class that enables an operator to insert + new individuals into the (intermediate) population. +*/ +template +class eoInserter : public eoObject +{ + public : + virtual ~eoInserter() {} + + struct eoInserterException{}; + + virtual void insert(const EOT&) = 0; // can throw an eoInserterException +}; + +/** + * eoPopInserter: In-between class that defines an initialization + * of the eoIndividualInserter. +*/ +template +class eoPopInserter : public eoInserter +{ + public : + + eoPopInserter(void) : thePop(0), eoInserter() {} + + /// Binds the population to this class. This is an initialization routine used by breeders + eoInserter& operator()(eoPop& _pop) + { + thePop = &_pop; + return *this; + } + + protected : + + eoPop& pop(void) const { valid(); return *thePop; } + + private : + + void valid(void) const + { + if (thePop == 0) + throw eoInserterException(); + } + + // Need a pointer as the inserter should be able to bind to different populations. + // This is caused by the 'one template parameter only' convention in EO. + + eoPop* thePop; + + // If eoGOpBreeder could be templatized over the inserter and the selector, + // the pop could be a ref as this class could be created every time it is applied + // and subsequently would get the population through the constructor + +}; + + + +#endif + diff --git a/eo/src/eoKill.h b/eo/src/eoKill.h index 826274f0..d6ad11c7 100644 --- a/eo/src/eoKill.h +++ b/eo/src/eoKill.h @@ -1,61 +1,62 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoKill.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EOKILL_h -#define _EOKILL_h - -#include - -#include - -/// Kill eliminates a gen in a chromosome -template -class eoKill: public eoMonOp { -public: - /// - eoKill( ) - : eoMonOp< EOT >(){}; - - /// needed virtual dtor - virtual ~eoKill() {}; - - /// - virtual void operator()( EOT& _eo ) const { - eoUniform uniform( 0, _eo.length() ); - unsigned pos = uniform( ); - _eo.deleteGene( pos ); - } - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoOp - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoKill";}; - //@} -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoKill.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOKILL_h +#define _EOKILL_h + +#include + +#include + +/// Kill eliminates a gen in a chromosome +template +class eoKill: public eoMonOp { +public: + /// + eoKill( ) + : eoMonOp< EOT >(){}; + + /// needed virtual dtor + virtual ~eoKill() {}; + + /// + virtual void operator()( EOT& _eo ) const { + eoUniform uniform( 0, _eo.length() ); + unsigned pos = uniform( ); + _eo.deleteGene( pos ); + } + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoOp + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoKill";}; + //@} +}; + +#endif + diff --git a/eo/src/eoLottery.h b/eo/src/eoLottery.h index 333ee792..9cf584bf 100644 --- a/eo/src/eoLottery.h +++ b/eo/src/eoLottery.h @@ -1,97 +1,98 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoLottery.h -// Implements the lottery procedure for selection -// (c) GeNeura Team, 1998 - Marc Schoenauer, 2000 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef eoLottery_h -#define eoLottery_h - -//----------------------------------------------------------------------------- - -#include // -#include // accumulate -#include "selectors.h" -#include // eoPop eoSelect MINFLOAT - -//----------------------------------------------------------------------------- -/** eoLottery: a selection method. Puts into the output a group of individuals - selected using lottery; individuals with higher probability will have more - chances of being selected. - Requires EOT::Fitness to be float castable -*/ -//----------------------------------------------------------------------------- - -template class eoLottery: public eoBinPopOp -{ - public: - /// (Default) Constructor. - eoLottery(const float& _rate = 1.0): eoBinPopOp(), rate(_rate) - { - if (minimizing_fitness()) - { - eoMinimizingFitnessException up(*this); - throw up; // :-) - } - } - - /** actually selects individuals from pop and pushes them back them into breeders - * until breeders has the right size: rate*pop.size() - * BUT what happens if breeders is already too big? - * Too big for what? - */ - void operator()( eoPop& pop, eoPop& breeders) - { - int target = (int)(rate * pop.size()); - - // test of consistency - if (breeders.size() >= target) { - throw("Problem in eoLottery: already too many offspring"); - } - - double total; - - try - { - total = sum_fitness(pop); - } - catch (eoNegativeFitnessException&) - { // say where it occured... - throw eoNegativeFitnessException(*this); - } - - // selection of chromosomes - while (breeders.size() < target) - { - breeders.push_back(roulette_wheel(pop, total)); - } - } - - double Rate(void) const { return rate; } - - private: - double rate; // selection rate -}; - -//----------------------------------------------------------------------------- - -#endif eoLottery_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoLottery.h +// Implements the lottery procedure for selection +// (c) GeNeura Team, 1998 - Marc Schoenauer, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoLottery_h +#define eoLottery_h + +//----------------------------------------------------------------------------- + +#include // +#include // accumulate +#include "selectors.h" +#include // eoPop eoSelect MINFLOAT + +//----------------------------------------------------------------------------- +/** eoLottery: a selection method. Puts into the output a group of individuals + selected using lottery; individuals with higher probability will have more + chances of being selected. + Requires EOT::Fitness to be float castable +*/ +//----------------------------------------------------------------------------- + +template class eoLottery: public eoBinPopOp +{ + public: + /// (Default) Constructor. + eoLottery(const float& _rate = 1.0): eoBinPopOp(), rate(_rate) + { + if (minimizing_fitness()) + { + eoMinimizingFitnessException up(*this); + throw up; // :-) + } + } + + /** actually selects individuals from pop and pushes them back them into breeders + * until breeders has the right size: rate*pop.size() + * BUT what happens if breeders is already too big? + * Too big for what? + */ + void operator()( eoPop& pop, eoPop& breeders) + { + int target = (int)(rate * pop.size()); + + // test of consistency + if (breeders.size() >= target) { + throw("Problem in eoLottery: already too many offspring"); + } + + double total; + + try + { + total = sum_fitness(pop); + } + catch (eoNegativeFitnessException&) + { // say where it occured... + throw eoNegativeFitnessException(*this); + } + + // selection of chromosomes + while (breeders.size() < target) + { + breeders.push_back(roulette_wheel(pop, total)); + } + } + + double Rate(void) const { return rate; } + + private: + double rate; // selection rate +}; + +//----------------------------------------------------------------------------- + +#endif eoLottery_h + diff --git a/eo/src/eoMultiBinOp.h b/eo/src/eoMultiBinOp.h index 231655b3..06237d84 100644 --- a/eo/src/eoMultiBinOp.h +++ b/eo/src/eoMultiBinOp.h @@ -1,99 +1,100 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoMultiBinOp.h -// Class that combines several binary or unary operators -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EOMULTIBINOP_h -#define _EOMULTIBINOP_h - -#include - -#include - -/** MultiMonOp combines several monary operators. By itself, it does nothing to the -EO it´s handled*/ -template -class eoMultiBinOp: public eoBinOp { -public: - /// Ctor from an already existing op - eoMultiBinOp( const eoBinOp* _op ) - : eoBinOp< EOT >( ), vOp(){ - vOp.push_back( _op ); - }; - - /// - eoMultiBinOp( ) - : eoBinOp< EOT >( ), vOp(){}; - - /// Ads a new operator - void adOp( const eoOp* _op ){ - vOp.push_back( _op ); - }; - - /// needed virtual dtor - virtual ~eoMultiBinOp() {}; - - /// - /// Applies all operators to the EO - virtual void operator()( EOT& _eo1, EOT& _eo2 ) const { - if ( vOp.begin() != vOp.end() ) { // which would mean it's empty - for ( vector< const eoOp* >::const_iterator i = vOp.begin(); - i != vOp.end(); i++ ) { - // Admits only unary or binary operator - switch ((*i)->readArity()) { - case unary: - { - const eoMonOp* monop = static_cast* >(*i); - (*monop)( _eo1 ); - (*monop)( _eo2 ); - break; - } - case binary: - { - const eoBinOp* binop = static_cast* >(*i); - (*binop)( _eo1, _eo2 ); - break; - } - } - } - } - } - - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoOp - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoMultiBinOp";}; - //@} - -private: - - /// uses pointers to base class since operators can be unary or binary - vector< const eoOp* > vOp; -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoMultiBinOp.h +// Class that combines several binary or unary operators +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOMULTIBINOP_h +#define _EOMULTIBINOP_h + +#include + +#include + +/** MultiMonOp combines several monary operators. By itself, it does nothing to the +EO it´s handled*/ +template +class eoMultiBinOp: public eoBinOp { +public: + /// Ctor from an already existing op + eoMultiBinOp( const eoBinOp* _op ) + : eoBinOp< EOT >( ), vOp(){ + vOp.push_back( _op ); + }; + + /// + eoMultiBinOp( ) + : eoBinOp< EOT >( ), vOp(){}; + + /// Ads a new operator + void adOp( const eoOp* _op ){ + vOp.push_back( _op ); + }; + + /// needed virtual dtor + virtual ~eoMultiBinOp() {}; + + /// + /// Applies all operators to the EO + virtual void operator()( EOT& _eo1, EOT& _eo2 ) const { + if ( vOp.begin() != vOp.end() ) { // which would mean it's empty + for ( vector< const eoOp* >::const_iterator i = vOp.begin(); + i != vOp.end(); i++ ) { + // Admits only unary or binary operator + switch ((*i)->readArity()) { + case unary: + { + const eoMonOp* monop = static_cast* >(*i); + (*monop)( _eo1 ); + (*monop)( _eo2 ); + break; + } + case binary: + { + const eoBinOp* binop = static_cast* >(*i); + (*binop)( _eo1, _eo2 ); + break; + } + } + } + } + } + + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoOp + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoMultiBinOp";}; + //@} + +private: + + /// uses pointers to base class since operators can be unary or binary + vector< const eoOp* > vOp; +}; + +#endif + diff --git a/eo/src/eoMultiMonOp.h b/eo/src/eoMultiMonOp.h index c06a2794..09167206 100644 --- a/eo/src/eoMultiMonOp.h +++ b/eo/src/eoMultiMonOp.h @@ -1,80 +1,80 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoMultiMonOp.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EOMULTIMONOP_h -#define _EOMULTIMONOP_h - -#include - -#include - -/** MultiMonOp combines several monary operators. By itself, it does nothing to the -EO it´s handled*/ -template -class eoMultiMonOp: public eoMonOp { -public: - /// Ctor from an already existing op - eoMultiMonOp( const eoMonOp* _op ) - : eoMonOp< EOT >( ), vOp(){ - vOp.push_back( _op ); - }; - - /// - eoMultiMonOp( ) - : eoMonOp< EOT >( ), vOp(){}; - - /// Ctor from an already existing op - void adOp( const eoMonOp* _op ){ - vOp.push_back( _op ); - }; - - /// needed virtual dtor - virtual ~eoMultiMonOp() {}; - - /// - /// Applies all operators to the EO - virtual void operator()( EOT& _eo ) const { - if ( vOp.begin() != vOp.end() ) { - for ( vector* >::const_iterator i = vOp.begin(); - i != vOp.end(); i++ ) { - (*i)->operator () ( _eo ); - } - } - } - - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoOp - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoMonOp";}; - //@} -private: - vector< const eoMonOp* > vOp; -}; - -#endif \ No newline at end of file +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoMultiMonOp.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOMULTIMONOP_h +#define _EOMULTIMONOP_h + +#include + +#include + +/** MultiMonOp combines several monary operators. By itself, it does nothing to the +EO it´s handled*/ +template +class eoMultiMonOp: public eoMonOp { +public: + /// Ctor from an already existing op + eoMultiMonOp( const eoMonOp* _op ) + : eoMonOp< EOT >( ), vOp(){ + vOp.push_back( _op ); + }; + + /// + eoMultiMonOp( ) + : eoMonOp< EOT >( ), vOp(){}; + + /// Ctor from an already existing op + void adOp( const eoMonOp* _op ){ + vOp.push_back( _op ); + }; + + /// needed virtual dtor + virtual ~eoMultiMonOp() {}; + + /// + /// Applies all operators to the EO + virtual void operator()( EOT& _eo ) const { + if ( vOp.begin() != vOp.end() ) { + for ( vector* >::const_iterator i = vOp.begin(); + i != vOp.end(); i++ ) { + (*i)->operator () ( _eo ); + } + } + } + + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoOp + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoMonOp";}; + //@} +private: + vector< const eoMonOp* > vOp; +}; + +#endif diff --git a/eo/src/eoMutation.h b/eo/src/eoMutation.h index fbc3641c..2c4672f6 100644 --- a/eo/src/eoMutation.h +++ b/eo/src/eoMutation.h @@ -1,90 +1,91 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoMutation.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- -#ifndef _EOMUTATION_H -#define _EOMUTATION_H - -#include -// EO includes -#include -#include - -/** Generic Mutation of an EO. - This is a virtual class, just to establish the interface for the ctor. - Mutation is usually type-specific -*/ - -template -class eoMutation: public eoMonOp { -public: - - /// - eoMutation(const double _rate=0.0) : eoMonOp< EOT >(), rate(_rate) {}; - - /// - virtual ~eoMutation() {}; - - /// - virtual void operator()( EOT& _eo ) const { - typename EOT::iterator i; - for ( i = _eo.begin(); i != _eo.end(); i ++ ) - applyAt( _eo, *i ); - } - - /// To print me on a stream. - /// @param os The ostream. - void printOn(ostream& os) const { - os << rate ; - } - - /// To read me from a stream. - /// @param is The istream. - void readFrom(istream& is) { - is >> rate ; - } - - /** @name Methods from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoMutation";}; - //@} - -protected: - double rate; - -private: -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - /// applies operator to one gene in the EO. It is empty, so each descent class must define it. - virtual void applyAt( EOT& _eo, unsigned _i ) const = 0 ; -}; - - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoMutation.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- +#ifndef _EOMUTATION_H +#define _EOMUTATION_H + +#include +// EO includes +#include +#include + +/** Generic Mutation of an EO. + This is a virtual class, just to establish the interface for the ctor. + Mutation is usually type-specific +*/ + +template +class eoMutation: public eoMonOp { +public: + + /// + eoMutation(const double _rate=0.0) : eoMonOp< EOT >(), rate(_rate) {}; + + /// + virtual ~eoMutation() {}; + + /// + virtual void operator()( EOT& _eo ) const { + typename EOT::iterator i; + for ( i = _eo.begin(); i != _eo.end(); i ++ ) + applyAt( _eo, *i ); + } + + /// To print me on a stream. + /// @param os The ostream. + void printOn(ostream& os) const { + os << rate ; + } + + /// To read me from a stream. + /// @param is The istream. + void readFrom(istream& is) { + is >> rate ; + } + + /** @name Methods from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoMutation";}; + //@} + +protected: + double rate; + +private: +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + /// applies operator to one gene in the EO. It is empty, so each descent class must define it. + virtual void applyAt( EOT& _eo, unsigned _i ) const = 0 ; +}; + + +#endif + diff --git a/eo/src/eoNegExp.h b/eo/src/eoNegExp.h index 63c9203e..7829a3c5 100644 --- a/eo/src/eoNegExp.h +++ b/eo/src/eoNegExp.h @@ -1,66 +1,67 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - ------------------------------------------------------------------------------ - eoNegExp.h - (c) GeNeura Team, 1998 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EONEGEXP_H -#define _EONEGEXP_H - -//----------------------------------------------------------------------------- - -#include - -#include // for base class -#include // for base class - -//----------------------------------------------------------------------------- -// Class eoNegExp -//----------------------------------------------------------------------------- - -/// Generates random numbers using a negative exponential distribution -template -class eoNegExp: public eoRnd -{ - public: - /** - * Default constructor. - * @param _mean Distribution mean - */ - eoNegExp(T _mean): eoRnd(), mean(_mean) {}; - - /** - * Copy constructor. - * @param _rnd the copyee - */ - eoNegExp( const eoNegExp& _rnd): eoRnd( _rnd), mean(_rnd.mean) {}; - - /// Returns an uniform dandom number over the interval [min, max). - virtual T operator()() { - return T( -mean*log((double)rng.rand() / rng.rand_max())); } - - private: - T mean; -}; - -//----------------------------------------------------------------------------- - -#endif +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +----------------------------------------------------------------------------- + eoNegExp.h + (c) GeNeura Team, 1998 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EONEGEXP_H +#define _EONEGEXP_H + +//----------------------------------------------------------------------------- + +#include + +#include // for base class +#include // for base class + +//----------------------------------------------------------------------------- +// Class eoNegExp +//----------------------------------------------------------------------------- + +/// Generates random numbers using a negative exponential distribution +template +class eoNegExp: public eoRnd +{ + public: + /** + * Default constructor. + * @param _mean Distribution mean + */ + eoNegExp(T _mean): eoRnd(), mean(_mean) {}; + + /** + * Copy constructor. + * @param _rnd the copyee + */ + eoNegExp( const eoNegExp& _rnd): eoRnd( _rnd), mean(_rnd.mean) {}; + + /// Returns an uniform dandom number over the interval [min, max). + virtual T operator()() { + return T( -mean*log((double)rng.rand() / rng.rand_max())); } + + private: + T mean; +}; + +//----------------------------------------------------------------------------- + +#endif + diff --git a/eo/src/eoNonUniform.h b/eo/src/eoNonUniform.h index c894806f..b5065d21 100644 --- a/eo/src/eoNonUniform.h +++ b/eo/src/eoNonUniform.h @@ -1,86 +1,87 @@ -//----------------------------------------------------------------------------- -// eoNonUniform.h -//----------------------------------------------------------------------------- - -#ifndef EONONUNIFORM_H -#define EONONUNIFORM_H - -//----------------------------------------------------------------------------- - -#include // pow - -//----------------------------------------------------------------------------- -// eoNonUniform -//----------------------------------------------------------------------------- - -class eoNonUniform -{ -public: - eoNonUniform(const unsigned _num_step): - step_value(0), num_step_value(_num_step) {} - - void reset() { step_value = 0; } - - const unsigned& step() const { return step_value; } - const unsigned& num_step() const { return num_step_value; } - - operator int() const { return step_value < num_step_value; } - - void operator++() { ++step_value; } - void operator++(int) { ++step_value; } - -private: - unsigned step_value, num_step_value; -}; - -//----------------------------------------------------------------------------- -// eoLinear -//----------------------------------------------------------------------------- - -class eoLinear -{ -public: - eoLinear(const double _first, - const double _last, - const eoNonUniform& _non_uniform): - first(_first), - diff((_last - _first) / (_non_uniform.num_step() - 1)), - non_uniform(_non_uniform) {} - - double operator()() const - { - return first + diff * non_uniform.step(); - } - -private: - double first, diff; - const eoNonUniform& non_uniform; -}; - -//----------------------------------------------------------------------------- -// eoNegExp2 -//----------------------------------------------------------------------------- - -class eoNegExp2 -{ - public: - eoNegExp2(const double _r, - const double _b, - const eoNonUniform& _non_uniform): - r(_r), b(_b), - non_uniform(_non_uniform) {} - - double operator()() const - { - return 1.0 - pow(r, pow(1.0 - (double)non_uniform.step() / - non_uniform.num_step(), b)); - } - - private: - double r, b; - const eoNonUniform& non_uniform; -}; - -//----------------------------------------------------------------------------- - -#endif NON_UNIFORM_HH +//----------------------------------------------------------------------------- +// eoNonUniform.h +//----------------------------------------------------------------------------- + +#ifndef EONONUNIFORM_H +#define EONONUNIFORM_H + +//----------------------------------------------------------------------------- + +#include // pow + +//----------------------------------------------------------------------------- +// eoNonUniform +//----------------------------------------------------------------------------- + +class eoNonUniform +{ +public: + eoNonUniform(const unsigned _num_step): + step_value(0), num_step_value(_num_step) {} + + void reset() { step_value = 0; } + + const unsigned& step() const { return step_value; } + const unsigned& num_step() const { return num_step_value; } + + operator int() const { return step_value < num_step_value; } + + void operator++() { ++step_value; } + void operator++(int) { ++step_value; } + +private: + unsigned step_value, num_step_value; +}; + +//----------------------------------------------------------------------------- +// eoLinear +//----------------------------------------------------------------------------- + +class eoLinear +{ +public: + eoLinear(const double _first, + const double _last, + const eoNonUniform& _non_uniform): + first(_first), + diff((_last - _first) / (_non_uniform.num_step() - 1)), + non_uniform(_non_uniform) {} + + double operator()() const + { + return first + diff * non_uniform.step(); + } + +private: + double first, diff; + const eoNonUniform& non_uniform; +}; + +//----------------------------------------------------------------------------- +// eoNegExp2 +//----------------------------------------------------------------------------- + +class eoNegExp2 +{ + public: + eoNegExp2(const double _r, + const double _b, + const eoNonUniform& _non_uniform): + r(_r), b(_b), + non_uniform(_non_uniform) {} + + double operator()() const + { + return 1.0 - pow(r, pow(1.0 - (double)non_uniform.step() / + non_uniform.num_step(), b)); + } + + private: + double r, b; + const eoNonUniform& non_uniform; +}; + +//----------------------------------------------------------------------------- + +#endif NON_UNIFORM_HH + diff --git a/eo/src/eoNormal.h b/eo/src/eoNormal.h index e7302c76..63904efc 100644 --- a/eo/src/eoNormal.h +++ b/eo/src/eoNormal.h @@ -1,88 +1,89 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoNormal.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EONORMAL_H -#define _EONORMAL_H - -//----------------------------------------------------------------------------- - -#include -#include // for base class -#include // for random number generator - -//----------------------------------------------------------------------------- -// Class eoNormal -//----------------------------------------------------------------------------- - -/// Generates random number using a normal distribution -template -class eoNormal: public eoRnd -{ - public: - /** - * Default constructor. - * @param _mean Dsitribution mean - * @param _sd Standard Deviation - */ - eoNormal(T _mean, T _sd) - : eoRnd(), mean(_mean), sd(_sd), phase(false) {} - - /** - * Copy constructor. - * @param _rnd the other one - */ - eoNormal( const eoNormal& _rnd ) - : eoRnd( _rnd), mean(_rnd.mean), sd(_rnd.sd), phase(false) {} - - /** Returns an uniform random number over the interval [min, max). - @return an uniform random number over the interval [min, max). - */ - virtual T operator()() { - if (phase) { // Already have one stored up. - phase = false; - return T ( (sqRatio * q * sd) + mean ); - } - - double p, v; - do { - p = ((double)rng.rand() / rng.rand_max())*2-1; - q = ((double)rng.rand() / rng.rand_max())*2-1; - v = p*p + q*q; - } while(v > 1.0 || v <0.25); - - sqRatio = sqrt(-2*log((double)rand() / rng.rand_max()) / v); - phase = true; - return T( (sqRatio * p * sd) + mean ); - }; - - private: - T mean; - T sd; - bool phase; - double sqRatio, q; -}; - -//----------------------------------------------------------------------------- - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoNormal.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EONORMAL_H +#define _EONORMAL_H + +//----------------------------------------------------------------------------- + +#include +#include // for base class +#include // for random number generator + +//----------------------------------------------------------------------------- +// Class eoNormal +//----------------------------------------------------------------------------- + +/// Generates random number using a normal distribution +template +class eoNormal: public eoRnd +{ + public: + /** + * Default constructor. + * @param _mean Dsitribution mean + * @param _sd Standard Deviation + */ + eoNormal(T _mean, T _sd) + : eoRnd(), mean(_mean), sd(_sd), phase(false) {} + + /** + * Copy constructor. + * @param _rnd the other one + */ + eoNormal( const eoNormal& _rnd ) + : eoRnd( _rnd), mean(_rnd.mean), sd(_rnd.sd), phase(false) {} + + /** Returns an uniform random number over the interval [min, max). + @return an uniform random number over the interval [min, max). + */ + virtual T operator()() { + if (phase) { // Already have one stored up. + phase = false; + return T ( (sqRatio * q * sd) + mean ); + } + + double p, v; + do { + p = ((double)rng.rand() / rng.rand_max())*2-1; + q = ((double)rng.rand() / rng.rand_max())*2-1; + v = p*p + q*q; + } while(v > 1.0 || v <0.25); + + sqRatio = sqrt(-2*log((double)rand() / rng.rand_max()) / v); + phase = true; + return T( (sqRatio * p * sd) + mean ); + }; + + private: + T mean; + T sd; + bool phase; + double sqRatio, q; +}; + +//----------------------------------------------------------------------------- + +#endif + diff --git a/eo/src/eoObject.h b/eo/src/eoObject.h index 0e2e9e68..82724ac2 100644 --- a/eo/src/eoObject.h +++ b/eo/src/eoObject.h @@ -1,68 +1,69 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoObject.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef EOOBJECT_H -#define EOOBJECT_H - -//----------------------------------------------------------------------------- - -#include // For limits definition -#include // istream, ostream -#include // string - -#include "compatibility.h" - -using namespace std; - -//----------------------------------------------------------------------------- -// eoObject -//----------------------------------------------------------------------------- -/** -This is the base class for the whole hierarchy; an eoObject defines -basically an interface for the whole hierarchy: each object should -know its name (#className#). Previously, this object defined a print and read -interface, but it´s been moved to eoPrintable and eoPersistent. - */ -class eoObject -{ - public: - - /// Default Constructor. - eoObject() {} - - /// Copy constructor. - eoObject( const eoObject& ) {} - - /// Virtual dtor. They are needed in virtual class hierarchies. - virtual ~eoObject() {} - - /** Return the class id. This should be redefined in each class; but - it's got code as an example of implementation. Only "leaf" classes - can be non-virtual. - */ - virtual string className() const { return "eoObject"; } - -}; - -#endif EOOBJECT_H +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoObject.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOOBJECT_H +#define EOOBJECT_H + +//----------------------------------------------------------------------------- + +#include // For limits definition +#include // istream, ostream +#include // string + +#include "compatibility.h" + +using namespace std; + +//----------------------------------------------------------------------------- +// eoObject +//----------------------------------------------------------------------------- +/** +This is the base class for the whole hierarchy; an eoObject defines +basically an interface for the whole hierarchy: each object should +know its name (#className#). Previously, this object defined a print and read +interface, but it´s been moved to eoPrintable and eoPersistent. + */ +class eoObject +{ + public: + + /// Default Constructor. + eoObject() {} + + /// Copy constructor. + eoObject( const eoObject& ) {} + + /// Virtual dtor. They are needed in virtual class hierarchies. + virtual ~eoObject() {} + + /** Return the class id. This should be redefined in each class; but + it's got code as an example of implementation. Only "leaf" classes + can be non-virtual. + */ + virtual string className() const { return "eoObject"; } + +}; + +#endif EOOBJECT_H + diff --git a/eo/src/eoOp.h b/eo/src/eoOp.h index dc81878c..232606c4 100644 --- a/eo/src/eoOp.h +++ b/eo/src/eoOp.h @@ -1,235 +1,236 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoOp.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _eoOp_H -#define _eoOp_H - -#include -#include - -/** @name Genetic operators - -What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with -eoOp as father and eoMonOp (monary or unary operator) and eoBinOp and eoQuadraticOp (binary operators) -as siblings). Nobody should subclass eoOp, you should subclass eoGeneralOp, eoBinOp, eoQuadraticOp or eoMonOp, -those are the ones actually used here.\\ - -#eoOp#s are only printable objects, so if you want to build them from a file, it has to -be done in another class, namely factories. Each hierarchy of #eoOp#s should have its own -factory, which know how to build them from a description in a file. -@author GeNeura Team -@version 0.1 -@see eoOpFactory -*/ - - -/** Abstract data types for EO operators. - * Genetic operators act on chromosomes, changing them. The type to instantiate them should - * be an eoObject, but in any case, they are type-specific; each kind of evolvable object - * can have its own operators - */ -template -class eoOp: public eoObject, public eoPrintable { -public: - -//@{ - enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3}; -/// - - /// Ctor - eoOp(OpType _type) - :opType( _type ) {}; - - /// Copy Ctor - eoOp( const eoOp& _eop ) - :opType( _eop.opType ) {}; - - /// Needed virtual destructor - virtual ~eoOp(){}; - - /// getType: number of operands it takes and individuals it produces - OpType getType() const {return opType;}; - - /** @name Methods from eoObject */ - //@{ - - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. - */ - virtual void printOn(ostream& _os) const { - _os << className().c_str(); - // _os << arity; - }; - - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoOp";}; - //@} - -private: - /// OpType is the type of the operator: how many operands it takes and how many it produces - OpType opType; - -}; - -/** Binary genetic operator: subclasses eoOp, and defines -basically the operator() with two operands -*/ -template -class eoBinOp: public eoOp { -public: - - /// Ctor - eoBinOp() - :eoOp( binary ) {}; - - /// Copy Ctor - eoBinOp( const eoBinOp& _ebop ) - : eoOp( _ebop ){}; - - /// Dtor - ~eoBinOp () {}; - - /** applies operator, to the object. Modifies only the first operand. - */ - virtual void operator()( EOType& _eo1, const EOType& _eo2 ) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoBinOp";}; - //@} - -}; - -/** Quadratic genetic operator: subclasses eoOp, and defines -basically the operator() with two operands -*/ -template -class eoQuadraticOp: public eoOp { -public: - - /// Ctor - eoQuadraticOp() - :eoOp( eoOp::quadratic ) {}; - - /// Copy Ctor - eoQuadraticOp( const eoQuadraticOp& _ebop ) - : eoOp( _ebop ){}; - - /// Dtor - ~eoQuadraticOp() {}; - - /** applies operator, to the object. Modifies both operands. - */ - virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoBinOp";}; - //@} - -}; - -/** eoMonOp is the monary operator: genetic operator that takes - only one EO -*/ -template -class eoMonOp: public eoOp { -public: - - /// Ctor - eoMonOp( ) - : eoOp( eoOp::unary ) {}; - - /// Copy Ctor - eoMonOp( const eoMonOp& _emop ) - : eoOp( _emop ){}; - - /// Dtor - ~eoMonOp() {}; - - /** applies randomly operator, to the object. If arity is more than 1, - * keeps a copy of the operand in a cache. - */ - virtual void operator()( EOType& _eo1) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoMonOp";}; - //@} -}; - -// some forward declarations -template -class eoIndiSelector; - -template -class eoInserter; - -/** - * eGeneralOp: General genetic operator; for objects used to transform sets - of EOs. Nary ("orgy") operators should be derived from this class -*/ -template -class eoGeneralOp: public eoOp -{ -public: - - /// Ctor that honors its superclass - eoGeneralOp(): eoOp( eoOp::general ) {}; - - /// Virtual dtor - virtual ~eoGeneralOp () {}; - - /** Method that really does the stuff. Applies the genetic operator - to a individuals dispensed by an eoIndividualSelector, - and puts the results in the eoIndividualInserter. - Any number of inputs can be requested and any number of outputs - can be produced. - */ - virtual void operator()( eoIndiSelector& _in, - eoInserter& _out) const = 0; - - virtual string className() const {return "eoGeneralOp";}; -}; - - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOp.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoOp_H +#define _eoOp_H + +#include +#include + +/** @name Genetic operators + +What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with +eoOp as father and eoMonOp (monary or unary operator) and eoBinOp and eoQuadraticOp (binary operators) +as siblings). Nobody should subclass eoOp, you should subclass eoGeneralOp, eoBinOp, eoQuadraticOp or eoMonOp, +those are the ones actually used here.\\ + +#eoOp#s are only printable objects, so if you want to build them from a file, it has to +be done in another class, namely factories. Each hierarchy of #eoOp#s should have its own +factory, which know how to build them from a description in a file. +@author GeNeura Team +@version 0.1 +@see eoOpFactory +*/ + + +/** Abstract data types for EO operators. + * Genetic operators act on chromosomes, changing them. The type to instantiate them should + * be an eoObject, but in any case, they are type-specific; each kind of evolvable object + * can have its own operators + */ +template +class eoOp: public eoObject, public eoPrintable { +public: + +//@{ + enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3}; +/// + + /// Ctor + eoOp(OpType _type) + :opType( _type ) {}; + + /// Copy Ctor + eoOp( const eoOp& _eop ) + :opType( _eop.opType ) {}; + + /// Needed virtual destructor + virtual ~eoOp(){}; + + /// getType: number of operands it takes and individuals it produces + OpType getType() const {return opType;}; + + /** @name Methods from eoObject */ + //@{ + + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A ostream. + */ + virtual void printOn(ostream& _os) const { + _os << className().c_str(); + // _os << arity; + }; + + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoOp";}; + //@} + +private: + /// OpType is the type of the operator: how many operands it takes and how many it produces + OpType opType; + +}; + +/** Binary genetic operator: subclasses eoOp, and defines +basically the operator() with two operands +*/ +template +class eoBinOp: public eoOp { +public: + + /// Ctor + eoBinOp() + :eoOp( binary ) {}; + + /// Copy Ctor + eoBinOp( const eoBinOp& _ebop ) + : eoOp( _ebop ){}; + + /// Dtor + ~eoBinOp () {}; + + /** applies operator, to the object. Modifies only the first operand. + */ + virtual void operator()( EOType& _eo1, const EOType& _eo2 ) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoBinOp";}; + //@} + +}; + +/** Quadratic genetic operator: subclasses eoOp, and defines +basically the operator() with two operands +*/ +template +class eoQuadraticOp: public eoOp { +public: + + /// Ctor + eoQuadraticOp() + :eoOp( eoOp::quadratic ) {}; + + /// Copy Ctor + eoQuadraticOp( const eoQuadraticOp& _ebop ) + : eoOp( _ebop ){}; + + /// Dtor + ~eoQuadraticOp() {}; + + /** applies operator, to the object. Modifies both operands. + */ + virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoBinOp";}; + //@} + +}; + +/** eoMonOp is the monary operator: genetic operator that takes + only one EO +*/ +template +class eoMonOp: public eoOp { +public: + + /// Ctor + eoMonOp( ) + : eoOp( eoOp::unary ) {}; + + /// Copy Ctor + eoMonOp( const eoMonOp& _emop ) + : eoOp( _emop ){}; + + /// Dtor + ~eoMonOp() {}; + + /** applies randomly operator, to the object. If arity is more than 1, + * keeps a copy of the operand in a cache. + */ + virtual void operator()( EOType& _eo1) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoMonOp";}; + //@} +}; + +// some forward declarations +template +class eoIndiSelector; + +template +class eoInserter; + +/** + * eGeneralOp: General genetic operator; for objects used to transform sets + of EOs. Nary ("orgy") operators should be derived from this class +*/ +template +class eoGeneralOp: public eoOp +{ +public: + + /// Ctor that honors its superclass + eoGeneralOp(): eoOp( eoOp::general ) {}; + + /// Virtual dtor + virtual ~eoGeneralOp () {}; + + /** Method that really does the stuff. Applies the genetic operator + to a individuals dispensed by an eoIndividualSelector, + and puts the results in the eoIndividualInserter. + Any number of inputs can be requested and any number of outputs + can be produced. + */ + virtual void operator()( eoIndiSelector& _in, + eoInserter& _out) const = 0; + + virtual string className() const {return "eoGeneralOp";}; +}; + + +#endif + diff --git a/eo/src/eoPersistent.cpp b/eo/src/eoPersistent.cpp index 2790534e..9bb76791 100644 --- a/eo/src/eoPersistent.cpp +++ b/eo/src/eoPersistent.cpp @@ -1,14 +1,15 @@ -#include - -//Implementation of these objects - -//----------------------------------------------------------------------------- - -istream & operator >> ( istream& _is, eoPersistent& _o ) { - _o.readFrom(_is); - return _is; -}; - -#include "eoRNG.h" - -eoRng rng; +#include + +//Implementation of these objects + +//----------------------------------------------------------------------------- + +istream & operator >> ( istream& _is, eoPersistent& _o ) { + _o.readFrom(_is); + return _is; +}; + +#include "eoRNG.h" + +eoRng rng; + diff --git a/eo/src/eoPersistent.h b/eo/src/eoPersistent.h index 2902e732..f02b4f5d 100644 --- a/eo/src/eoPersistent.h +++ b/eo/src/eoPersistent.h @@ -1,70 +1,74 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoPersistent.h -// (c) GeNeura Team, 1999 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef EOPERSISTENT_H -#define EOPERSISTENT_H - -/// @name variables Some definitions of variables used throughout the program -//@{ -/// max length to store stuff read -const unsigned MAXLINELENGTH=1024; -//@} - -//----------------------------------------------------------------------------- - -#include // istream, ostream -#include // para string - -//----------------------------------------------------------------------------- -#include - -using namespace std; - -//----------------------------------------------------------------------------- -// eoPersistent -//----------------------------------------------------------------------------- -/** -An persistent object that knows how to write (through functions inherited from -#eoPrintable#) and read itself - */ -class eoPersistent: public eoPrintable -{ - public: - /// Virtual dtor. They are needed in virtual class hierarchies. - virtual ~eoPersistent() {} - - /** - * Read object. - * @param _is A istream. - * @throw runtime_exception If a valid object can't be read. - */ - virtual void readFrom(istream& _is) = 0; - -}; - -//----------------------------------------------------------------------------- -///Standard input for all objects in the EO hierarchy -istream & operator >> ( istream& _is, eoPersistent& _o ); - -#endif EOOBJECT_H +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + + +//----------------------------------------------------------------------------- + +// eoPersistent.h +// (c) GeNeura Team, 1999 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOPERSISTENT_H +#define EOPERSISTENT_H + +/// @name variables Some definitions of variables used throughout the program +//@{ +/// max length to store stuff read +const unsigned MAXLINELENGTH=1024; +//@} + +//----------------------------------------------------------------------------- + +#include // istream, ostream +#include // para string + +//----------------------------------------------------------------------------- +#include + +using namespace std; + +//----------------------------------------------------------------------------- +// eoPersistent +//----------------------------------------------------------------------------- +/** +An persistent object that knows how to write (through functions inherited from +#eoPrintable#) and read itself + */ +class eoPersistent: public eoPrintable +{ + public: + /// Virtual dtor. They are needed in virtual class hierarchies. + virtual ~eoPersistent() {} + + /** + * Read object. + * @param _is A istream. + * @throw runtime_exception If a valid object can't be read. + */ + virtual void readFrom(istream& _is) = 0; + +}; + +//----------------------------------------------------------------------------- +///Standard input for all objects in the EO hierarchy +istream & operator >> ( istream& _is, eoPersistent& _o ); + +#endif EOOBJECT_H + diff --git a/eo/src/eoPop.h b/eo/src/eoPop.h index ebd86490..d988b3eb 100644 --- a/eo/src/eoPop.h +++ b/eo/src/eoPop.h @@ -1,160 +1,161 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoPop.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EOPOP_H -#define _EOPOP_H - -#include -#include - -// EO includes -#include -#include -#include - -/** Subpopulation: it is used to move parts of population - from one algorithm to another and one population to another. It is safer -to declare it as a separate object. I have no idea if a population can be -some other thing that a vector, but if somebody thinks of it, this concrete -implementation will be moved to "generic" and an abstract Population -interface will be provided. -It can be instantiated with anything, provided that it accepts a "size" and a -random generator in the ctor. This happens to all the eo1d chromosomes declared -so far. EOT must also have a copy ctor, since temporaries are created and copied -to the population. -@author Geneura Team -@version 0.0 -*/ - -template -class eoPop: public vector, public eoObject, public eoPersistent { - -/// Type is the type of each gene in the chromosome -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - public: - /** Protected ctor. This is intended to avoid creation of void populations, except - from sibling classes - */ - eoPop() :vector() {}; - - - /** Ctor for fixed-size chromosomes, with variable content - @param _popSize total population size - @param _eoSize chromosome size. EOT should accept a fixed-size ctor - @param _geneRdn random number generator for each of the genes - */ - eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd ) - :vector() { - for ( unsigned i = 0; i < _popSize; i ++ ){ - EOT tmpEOT( _eoSize, _geneRnd); - push_back( tmpEOT ); - } - }; - - /** Ctor for variable-size chromosomes, with variable content - @param _popSize total population size - @param _sizeRnd RNG for the chromosome size. This will be added 1, just in case. - @param _geneRdn random number generator for each of the genes - */ - eoPop( unsigned _popSize, eoRnd & _sizeRnd, eoRnd & _geneRnd ) - :vector() { - for ( unsigned i = 0; i < _popSize; i ++ ){ - unsigned size = 1 + _sizeRnd(); - EOT tmpEOT( size, _geneRnd); - push_back( tmpEOT ); - } - }; - - /** Ctor for fixed-size chromosomes, with variable content - @param _popSize total population size - @param _eoSize chromosome size. EOT should accept a fixed-size ctor - @param _geneRdn random number generator for each of the genes - */ - eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd, eoEvalFunc& _eval) - :vector() { - for ( unsigned i = 0; i < _popSize; i ++ ){ - EOT tmpEOT( _eoSize, _geneRnd); - push_back( tmpEOT ); - _eval(back()); - } - }; - - - /** Ctor from an istream; reads the population from a stream, - each element should be in different lines - @param _is the stream - */ - eoPop( istream& _is ):vector() { - readFrom( _is ); - } - - /// - ~eoPop() {}; - - /** @name Methods from eoObject */ - //@{ - /** - * Read object. The EOT class must have a ctor from a stream; - in this case, a strstream is used. - * @param _is A istream. - - */ - virtual void readFrom(istream& _is) { - while( _is ) { // reads line by line, and creates an object per - // line - char line[MAXLINELENGTH]; - _is.getline( line, MAXLINELENGTH-1 ); - if (strlen( line ) ) { - istrstream s( line ); - EOT thisEOT( s ); - push_back( thisEOT ); - } - } - } - - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. In this case, prints the population to - standard output. The EOT class must hav standard output with cout, - but since it should be an eoObject anyways, it's no big deal. - */ - virtual void printOn(ostream& _os) const { - copy( begin(), end(), ostream_iterator( _os, "\n") ); - }; - - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - virtual string className() const {return "eoPop";}; - //@} - - protected: - -}; -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPop.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOPOP_H +#define _EOPOP_H + +#include +#include + +// EO includes +#include +#include +#include + +/** Subpopulation: it is used to move parts of population + from one algorithm to another and one population to another. It is safer +to declare it as a separate object. I have no idea if a population can be +some other thing that a vector, but if somebody thinks of it, this concrete +implementation will be moved to "generic" and an abstract Population +interface will be provided. +It can be instantiated with anything, provided that it accepts a "size" and a +random generator in the ctor. This happens to all the eo1d chromosomes declared +so far. EOT must also have a copy ctor, since temporaries are created and copied +to the population. +@author Geneura Team +@version 0.0 +*/ + +template +class eoPop: public vector, public eoObject, public eoPersistent { + +/// Type is the type of each gene in the chromosome +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + public: + /** Protected ctor. This is intended to avoid creation of void populations, except + from sibling classes + */ + eoPop() :vector() {}; + + + /** Ctor for fixed-size chromosomes, with variable content + @param _popSize total population size + @param _eoSize chromosome size. EOT should accept a fixed-size ctor + @param _geneRdn random number generator for each of the genes + */ + eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd ) + :vector() { + for ( unsigned i = 0; i < _popSize; i ++ ){ + EOT tmpEOT( _eoSize, _geneRnd); + push_back( tmpEOT ); + } + }; + + /** Ctor for variable-size chromosomes, with variable content + @param _popSize total population size + @param _sizeRnd RNG for the chromosome size. This will be added 1, just in case. + @param _geneRdn random number generator for each of the genes + */ + eoPop( unsigned _popSize, eoRnd & _sizeRnd, eoRnd & _geneRnd ) + :vector() { + for ( unsigned i = 0; i < _popSize; i ++ ){ + unsigned size = 1 + _sizeRnd(); + EOT tmpEOT( size, _geneRnd); + push_back( tmpEOT ); + } + }; + + /** Ctor for fixed-size chromosomes, with variable content + @param _popSize total population size + @param _eoSize chromosome size. EOT should accept a fixed-size ctor + @param _geneRdn random number generator for each of the genes + */ + eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd, eoEvalFunc& _eval) + :vector() { + for ( unsigned i = 0; i < _popSize; i ++ ){ + EOT tmpEOT( _eoSize, _geneRnd); + push_back( tmpEOT ); + _eval(back()); + } + }; + + + /** Ctor from an istream; reads the population from a stream, + each element should be in different lines + @param _is the stream + */ + eoPop( istream& _is ):vector() { + readFrom( _is ); + } + + /// + ~eoPop() {}; + + /** @name Methods from eoObject */ + //@{ + /** + * Read object. The EOT class must have a ctor from a stream; + in this case, a strstream is used. + * @param _is A istream. + + */ + virtual void readFrom(istream& _is) { + while( _is ) { // reads line by line, and creates an object per + // line + char line[MAXLINELENGTH]; + _is.getline( line, MAXLINELENGTH-1 ); + if (strlen( line ) ) { + istrstream s( line ); + EOT thisEOT( s ); + push_back( thisEOT ); + } + } + } + + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A ostream. In this case, prints the population to + standard output. The EOT class must hav standard output with cout, + but since it should be an eoObject anyways, it's no big deal. + */ + virtual void printOn(ostream& _os) const { + copy( begin(), end(), ostream_iterator( _os, "\n") ); + }; + + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual string className() const {return "eoPop";}; + //@} + + protected: + +}; +#endif + diff --git a/eo/src/eoPrintable.h b/eo/src/eoPrintable.h index 9757d36c..bf7c4ccb 100644 --- a/eo/src/eoPrintable.h +++ b/eo/src/eoPrintable.h @@ -1,62 +1,63 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoPrintable.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef EOPRINTABLE_H -#define EOPRINTABLE_H - -//----------------------------------------------------------------------------- - -#include // istream, ostream -#include // para string - -using namespace std; - -//----------------------------------------------------------------------------- -// eoPrintable -//----------------------------------------------------------------------------- -/** -Base class for objects that can print themselves -(#printOn#). Besides, this file defines the standard output for all the objects; -if the objects define printOn there's no need to define #operator <<#.\\ -This functionality was separated from eoObject, since it makes no sense to print -some objects (for instance, a #eoFactory# or a random number generator. - */ -class eoPrintable -{ - public: - /// Virtual dtor. They are needed in virtual class hierarchies. - virtual ~eoPrintable() {} - - /** - * Write object. It's called printOn since it prints the object on a stream. - * @param _os A ostream. - */ - virtual void printOn(ostream& _os) const = 0; -}; - -//----------------------------------------------------------------------------- -///Standard output for all objects in the EO hierarchy -ostream & operator << ( ostream& _os, const eoPrintable& _o ); - -#endif EOPRINTABLE_H +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPrintable.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOPRINTABLE_H +#define EOPRINTABLE_H + +//----------------------------------------------------------------------------- + +#include // istream, ostream +#include // para string + +using namespace std; + +//----------------------------------------------------------------------------- +// eoPrintable +//----------------------------------------------------------------------------- +/** +Base class for objects that can print themselves +(#printOn#). Besides, this file defines the standard output for all the objects; +if the objects define printOn there's no need to define #operator <<#.\\ +This functionality was separated from eoObject, since it makes no sense to print +some objects (for instance, a #eoFactory# or a random number generator. + */ +class eoPrintable +{ + public: + /// Virtual dtor. They are needed in virtual class hierarchies. + virtual ~eoPrintable() {} + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A ostream. + */ + virtual void printOn(ostream& _os) const = 0; +}; + +//----------------------------------------------------------------------------- +///Standard output for all objects in the EO hierarchy +ostream & operator << ( ostream& _os, const eoPrintable& _o ); + +#endif EOPRINTABLE_H + diff --git a/eo/src/eoProblem.h b/eo/src/eoProblem.h index 892a14e4..5c219123 100644 --- a/eo/src/eoProblem.h +++ b/eo/src/eoProblem.h @@ -1,40 +1,45 @@ -//----------------------------------------------------------------------------- -// eoProblem.h -// (c) GeNeura Team 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef EOPROBLEM_H -#define EOPROBLEM_H - -//----------------------------------------------------------------------------- - -template class Problem -{ - public: - typedef T Chrom; - typedef typename T::Gene Gene; - typedef typename T::Fitness Fitness; - - virtual Fitness operator()(const Chrom& chrom) = 0; -}; - -//----------------------------------------------------------------------------- - -#endif EOPROBLEM_H +//----------------------------------------------------------------------------- + +// eoProblem.h + +// (c) GeNeura Team 1998 + +/* + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOPROBLEM_H +#define EOPROBLEM_H + +//----------------------------------------------------------------------------- + +template class Problem +{ + public: + typedef T Chrom; + typedef typename T::Gene Gene; + typedef typename T::Fitness Fitness; + + virtual Fitness operator()(const Chrom& chrom) = 0; +}; + +//----------------------------------------------------------------------------- + +#endif EOPROBLEM_H + diff --git a/eo/src/eoProportionalGOpSelector.h b/eo/src/eoProportionalGOpSelector.h index 6a1b2d97..580b7bf1 100644 --- a/eo/src/eoProportionalGOpSelector.h +++ b/eo/src/eoProportionalGOpSelector.h @@ -1,54 +1,55 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoProportionalGOpSelector.h - Proportional Generalized Operator Selector. - - (c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es -*/ - -#ifndef eoProportionalGOpSelector_h -#define eoProportionalGOpSelector_h - -//----------------------------------------------------------------------------- - -#include "eoGOpSelector.h" - -/** eoProportionalGOpSel: do proportional selection, returns one of the - operators -*/ -template -class eoProportionalGOpSel : public eoGOpSelector -{ -public : - eoProportionalGOpSel() : eoGOpSelector() {} - - /** Returns the operator proportionally selected */ - virtual eoGeneralOp& selectOp() - { - unsigned what = rng.roulette_wheel(getRates()); - return *operator[](what); - } - - /// - virtual string className() const { return "eoGOpSelector"; }; -}; - -#endif - +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoProportionalGOpSelector.h + Proportional Generalized Operator Selector. + + (c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es +*/ + +#ifndef eoProportionalGOpSelector_h +#define eoProportionalGOpSelector_h + +//----------------------------------------------------------------------------- + +#include "eoGOpSelector.h" + +/** eoProportionalGOpSel: do proportional selection, returns one of the + operators +*/ +template +class eoProportionalGOpSel : public eoGOpSelector +{ +public : + eoProportionalGOpSel() : eoGOpSelector() {} + + /** Returns the operator proportionally selected */ + virtual eoGeneralOp& selectOp() + { + unsigned what = rng.roulette_wheel(getRates()); + return *operator[](what); + } + + /// + virtual string className() const { return "eoGOpSelector"; }; +}; + +#endif + + diff --git a/eo/src/eoProportionalOpSel.h b/eo/src/eoProportionalOpSel.h index 1ea9fbc6..0a48a620 100644 --- a/eo/src/eoProportionalOpSel.h +++ b/eo/src/eoProportionalOpSel.h @@ -1,154 +1,159 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoProportionalOpSel.h -// (c) GeNeura Team 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef EOPROPORTIONALOPSEL_H -#define EOPROPORTIONALOPSEL_H - -//----------------------------------------------------------------------------- - -#include // runtime_error -#include // greater -#include - -// Includes from EO -#include -#include -#include - -//----------------------------------------------------------------------------- -/** This class selects operators according to probability. All operator percentages -should add up to one; if not, an exception will be raised.\\ -Operators are represented as pairs (proportion,operator) -*/ -template -class eoProportionalOpSel: public eoOpSelector, - public multimap*,greater > -{ -public: - - typedef multimap*,greater > MMF; - - /// default ctor - eoProportionalOpSel() - : eoOpSelector(), MMF(), opID(1) {}; - - /// virtual dtor - virtual ~eoProportionalOpSel() {}; - - /** Gets a non-const reference to an operator, so that it can be changed, - modified or whatever - @param _id a previously assigned ID - @throw runtime_error if the ID does not exist*/ - - virtual eoOp& getOp( ID _id ) { - MMF::iterator i=begin(); - ID j = 1; - while ( (i++!=end()) && (j++ != _id) ); - if ( i == end() ) - throw runtime_error( "No such id in eoProportionalOpSel::op\n" ); - return *(i->second); - //return i->second; - } - - /** add an operator to the operator set - @param _op a genetic operator, that will be applied in some way - @param _arg an argument to the operator, usually operator rate - @return an ID that will be used to identify the operator - */ - virtual ID addOp( eoOp& _op, float _arg ) { - insert( MMF::value_type( _arg,& _op ) ); - return opID++; - } - - /** Remove an operator from the operator set - @param _id a previously assigned ID - @throw runtime_error if the ID does not exist - */ - virtual void deleteOp( ID _id ) { - unsigned j; - MMF::iterator i; - for ( i=begin(), j=1; i!=end(); i++,j++ ) { - if( j == _id ) - erase( i ); - return; - } - if ( i == end() ) - throw runtime_error( "No such id in eoProportionalOpSel::op\n" ); - }; - - /// Returns a genetic operator according to the established criteria - virtual eoOp* Op() { - // Check that all add up to one - float acc = 0; - MMF::iterator i; - unsigned j; - for ( i=begin(), j=1; i!=end(); i++,j++ ) { - acc +=i->first; - } - if ( acc != 1.0 ) - throw runtime_error( "Operator rates added up different from 1.0" ); - - // If here, operators ordered by rate and no problem - eoUniform u(0,1.0); - float aRnd = u(); - i=begin(); - acc = 0; - do { - acc += i->first; - } while ( (acc <= aRnd ) && (i++!=end() ) ); - if ( i == end() ) - throw runtime_error( "Operator not found in eoProportionalOpSelector" ); - return i->second; - //return i->second; - } - - /// Methods inherited from eoObject - //@{ - - /** Return the class id. - @return the class name as a string - */ - virtual string className() const { return "eoProportionalOpSel"; }; - - /** Print itself: inherited from eoObject implementation. Declared virtual so that - it can be reimplemented anywhere. Instance from base classes are processed in - base classes, so you don´t have to worry about, for instance, fitness. - @param _s the ostream in which things are written*/ - virtual void printOn( ostream& _s ) const{ - _s << className().c_str() << endl; - for ( MMF::const_iterator i=begin(); i!=end(); i++ ) { - _s << i->first << "\t" << *(i->second )<< endl; - } - } - - - //@} - - private: - ID opID; - }; - - //----------------------------------------------------------------------------- - -#endif EO_H +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + + +//----------------------------------------------------------------------------- + +// eoProportionalOpSel.h + +// (c) GeNeura Team 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef EOPROPORTIONALOPSEL_H +#define EOPROPORTIONALOPSEL_H + +//----------------------------------------------------------------------------- + +#include // runtime_error +#include // greater +#include + +// Includes from EO +#include +#include +#include + +//----------------------------------------------------------------------------- +/** This class selects operators according to probability. All operator percentages +should add up to one; if not, an exception will be raised.\\ +Operators are represented as pairs (proportion,operator) +*/ +template +class eoProportionalOpSel: public eoOpSelector, + public multimap*,greater > +{ +public: + + typedef multimap*,greater > MMF; + + /// default ctor + eoProportionalOpSel() + : eoOpSelector(), MMF(), opID(1) {}; + + /// virtual dtor + virtual ~eoProportionalOpSel() {}; + + /** Gets a non-const reference to an operator, so that it can be changed, + modified or whatever + @param _id a previously assigned ID + @throw runtime_error if the ID does not exist*/ + + virtual eoOp& getOp( ID _id ) { + MMF::iterator i=begin(); + ID j = 1; + while ( (i++!=end()) && (j++ != _id) ); + if ( i == end() ) + throw runtime_error( "No such id in eoProportionalOpSel::op\n" ); + return *(i->second); + //return i->second; + } + + /** add an operator to the operator set + @param _op a genetic operator, that will be applied in some way + @param _arg an argument to the operator, usually operator rate + @return an ID that will be used to identify the operator + */ + virtual ID addOp( eoOp& _op, float _arg ) { + insert( MMF::value_type( _arg,& _op ) ); + return opID++; + } + + /** Remove an operator from the operator set + @param _id a previously assigned ID + @throw runtime_error if the ID does not exist + */ + virtual void deleteOp( ID _id ) { + unsigned j; + MMF::iterator i; + for ( i=begin(), j=1; i!=end(); i++,j++ ) { + if( j == _id ) + erase( i ); + return; + } + if ( i == end() ) + throw runtime_error( "No such id in eoProportionalOpSel::op\n" ); + }; + + /// Returns a genetic operator according to the established criteria + virtual eoOp* Op() { + // Check that all add up to one + float acc = 0; + MMF::iterator i; + unsigned j; + for ( i=begin(), j=1; i!=end(); i++,j++ ) { + acc +=i->first; + } + if ( acc != 1.0 ) + throw runtime_error( "Operator rates added up different from 1.0" ); + + // If here, operators ordered by rate and no problem + eoUniform u(0,1.0); + float aRnd = u(); + i=begin(); + acc = 0; + do { + acc += i->first; + } while ( (acc <= aRnd ) && (i++!=end() ) ); + if ( i == end() ) + throw runtime_error( "Operator not found in eoProportionalOpSelector" ); + return i->second; + //return i->second; + } + + /// Methods inherited from eoObject + //@{ + + /** Return the class id. + @return the class name as a string + */ + virtual string className() const { return "eoProportionalOpSel"; }; + + /** Print itself: inherited from eoObject implementation. Declared virtual so that + it can be reimplemented anywhere. Instance from base classes are processed in + base classes, so you don´t have to worry about, for instance, fitness. + @param _s the ostream in which things are written*/ + virtual void printOn( ostream& _s ) const{ + _s << className().c_str() << endl; + for ( MMF::const_iterator i=begin(); i!=end(); i++ ) { + _s << i->first << "\t" << *(i->second )<< endl; + } + } + + + //@} + + private: + ID opID; + }; + + //----------------------------------------------------------------------------- + +#endif EO_H + diff --git a/eo/src/eoRNG.h b/eo/src/eoRNG.h index b560e7c1..18bf2566 100644 --- a/eo/src/eoRNG.h +++ b/eo/src/eoRNG.h @@ -1,452 +1,453 @@ -/* -* Random number generator adapted from (see comments below) -* -* The random number generator is modified into a class -* by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller -* transformation to generate normal deviates. -* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es -*/ - -/* ************ DOCUMENTATION IN ORIGINAL FILE *********************/ - -// This is the ``Mersenne Twister'' random number generator MT19937, which -// generates pseudorandom integers uniformly distributed in 0..(2^32 - 1) -// starting from any odd seed in 0..(2^32 - 1). This version is a recode -// by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by -// Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in -// July-August 1997). -// -// Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha -// running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to -// generate 300 million random numbers; after recoding: 24.0 sec. for the same -// (i.e., 46.5% of original time), so speed is now about 12.5 million random -// number generations per second on this machine. -// -// According to the URL -// (and paraphrasing a bit in places), the Mersenne Twister is ``designed -// with consideration of the flaws of various existing generators,'' has -// a period of 2^19937 - 1, gives a sequence that is 623-dimensionally -// equidistributed, and ``has passed many stringent tests, including the -// die-hard test of G. Marsaglia and the load test of P. Hellekalek and -// S. Wegenkittl.'' It is efficient in memory usage (typically using 2506 -// to 5012 bytes of static data, depending on data type sizes, and the code -// is quite short as well). It generates random numbers in batches of 624 -// at a time, so the caching and pipelining of modern systems is exploited. -// It is also divide- and mod-free. -// -// This library is free software; you can redistribute it and/or modify it -// under the terms of the GNU Library General Public License as published by -// the Free Software Foundation (either version 2 of the License or, at your -// option, any later version). This library is distributed in the hope that -// it will be useful, but WITHOUT ANY WARRANTY, without even the implied -// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See -// the GNU Library General Public License for more details. You should have -// received a copy of the GNU Library General Public License along with this -// library; if not, write to the Free Software Foundation, Inc., 59 Temple -// Place, Suite 330, Boston, MA 02111-1307, USA. -// -// The code as Shawn received it included the following notice: -// -// Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When -// you use this, send an e-mail to with -// an appropriate reference to your work. -// -// It would be nice to CC: when you write. -// - -// -// uint32 must be an unsigned integer type capable of holding at least 32 -// bits; exactly 32 should be fastest, but 64 is better on an Alpha with -// GCC at -O3 optimization so try your options and see what's best for you -// - -/* ************ END DOCUMENTATION IN ORIGINAL FILE *********************/ - - -#ifndef EO_RANDOM_NUMBER_GENERATOR -#define EO_RANDOM_NUMBER_GENERATOR - -#include - -#include -#include - -// TODO: check for various compilers if this is exactly 32 bits -// Unfortunately MSVC's preprocessor does not comprehends sizeof() -// so neat preprocessing tricks will not work - -typedef unsigned long uint32; // Compiler and platform dependent! - -//----------------------------------------------------------------------------- -// eoRng -//----------------------------------------------------------------------------- -/** -eoRng is a persitent class that uses the ``Mersenne Twister'' random number generator MT19937 -for generating random numbers. The various member functions implement useful functions -for evolutionary algorithms. Included are: rand(), random(), flip() and normal(). - -Note for people porting EO to other platforms: please make sure that the typedef -uint32 in the file eoRng.h is exactly 32 bits long. It may be longer, but not -shorter. If it is longer, file compatibility between EO on different platforms -may be broken. -*/ -class eoRng : public eoObject, public eoPersistent -{ -public : - /** - ctor takes a random seed; if you want another seed, use reseed - @see reseed - */ - - eoRng(uint32 s = (uint32) time(0) ) : state(0), next(0), left(-1), cached(false), N(624), M(397), K(0x9908B0DFU) { - state = new uint32[N+1]; - initialize(s); - } - - ~eoRng(void) - { - delete [] state; - } - - /** - Re-initializes the Random Number Generator. - */ - void reseed(uint32 s) - { - initialize(s); - } - - /** - uniform(m = 1.0) returns a random double in the range [0, m) - */ - double uniform(double m = 1.0) - { // random number between [0, m] - return m * double(rand()) / double(rand_max()); - } - - /** - random() returns a random integer in the range [0, m) - */ - uint32 random(uint32 m) - { - return uint32(uniform() * double(m)); - } - - /** - flip() tosses a biased coin such that flip(x/100.0) will - returns true x% of the time - */ - bool flip(float bias) - { - return uniform() < bias; - } - - /** - normal() zero mean gaussian deviate with standard deviation of 1 - */ - double normal(void); // gaussian mutation, stdev 1 - - /** - normal(stdev) zero mean gaussian deviate with user defined standard deviation - */ - double normal(double stdev) - { - return stdev * normal(); - } - - /** - normal(mean, stdev) user defined mean gaussian deviate with user defined standard deviation - */ - double normal(double mean, double stdev) - { - return mean + normal(stdev); - } - - /** - rand() returns a random number in the range [0, rand_max) - */ - uint32 rand(); - - /** - rand_max() the maximum returned by rand() - */ - uint32 rand_max(void) const { return (uint32) 0xffffffff; } - - /** - roulette_wheel(vec, total = 0) does a roulette wheel selection - on the input vector vec. If the total is not supplied, it is - calculated. It returns an integer denoting the selected argument. - */ - template - int roulette_wheel(const std::vector& vec, T total = 0) - { - if (total == 0) - { // count - for (int i = 0; i < vec.size(); ++i) - total += vec[i]; - } - - float change = uniform() * total; - - int i = 0; - - while (change > 0) - { - change -= vec[i++]; - } - - return --i; - } - - /// - void printOn(ostream& _os) const - { - for (int i = 0; i < N; ++i) - { - _os << state[i] << ' '; - } - _os << int(next - state) << ' '; - _os << left << ' ' << cached << ' ' << cacheValue; - } - - /// - void readFrom(istream& _is) - { - for (int i = 0; i < N; ++i) - { - _is >> state[i]; - } - - int n; - _is >> n; - next = state + n; - - _is >> left; - _is >> cached; - _is >> cacheValue; - } - - -private : - uint32 restart(void); - void initialize(uint32 seed); - - uint32* state; // the array for the state - uint32* next; - int left; - - bool cached; - float cacheValue; - - const int N; - const int M; - const uint32 K; // a magic constant - - /** - Private copy ctor and assignment operator to make sure that - nobody accidentally copies the random number generator. - If you want similar RNG's, make two RNG's and initialize - them with the same seed. - */ - eoRng (const eoRng&); // no implementation - eoRng& operator=(const eoRng&); // dito -}; - -/** - The one and only global eoRng object -*/ -extern eoRng rng; - -/** - The class uniform_generator can be used in the STL generate function - to easily generate random floats and doubles between [0, _max). _max - defaults to 1.0 -*/ -template class uniform_generator -{ - public : - uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {} - - virtual T operator()(void) { return (T) uniform.uniform(maxim); } - private : - T maxim; - eoRng& uniform; -}; - -/** - The class random_generator can be used in the STL generate function - to easily generate random ints between [0, _max). -*/ -template class random_generator -{ - public : - random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {} - - virtual T operator()(void) { return (T) random.random(max); } - - private : - T maxim; - eoRng& random; -}; - -/** - The class normal_generator can be used in the STL generate function - to easily generate gaussian distributed floats and doubles. The user - can supply a standard deviation which defaults to 1. -*/ -template class normal_generator -{ - public : - normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} - - virtual T operator()(void) { return (T) normal.normal(stdev); } - - private : - T stdev; - eoRng& normal; -}; - -// Implementation of some eoRng members.... Don't mind the mess, it does work. - - -#define hiBit(u) ((u) & 0x80000000U) // mask all but highest bit of u -#define loBit(u) ((u) & 0x00000001U) // mask all but lowest bit of u -#define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u -#define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v - -inline void eoRng::initialize(uint32 seed) - { - // - // We initialize state[0..(N-1)] via the generator - // - // x_new = (69069 * x_old) mod 2^32 - // - // from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's - // _The Art of Computer Programming_, Volume 2, 3rd ed. - // - // Notes (SJC): I do not know what the initial state requirements - // of the Mersenne Twister are, but it seems this seeding generator - // could be better. It achieves the maximum period for its modulus - // (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if - // x_initial can be even, you have sequences like 0, 0, 0, ...; - // 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31, - // 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below. - // - // Even if x_initial is odd, if x_initial is 1 mod 4 then - // - // the lowest bit of x is always 1, - // the next-to-lowest bit of x is always 0, - // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , - // the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... , - // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... , - // ... - // - // and if x_initial is 3 mod 4 then - // - // the lowest bit of x is always 1, - // the next-to-lowest bit of x is always 1, - // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , - // the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... , - // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... , - // ... - // - // The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is - // 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It - // also does well in the dimension 2..5 spectral tests, but it could be - // better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth). - // - // Note that the random number user does not see the values generated - // here directly since restart() will always munge them first, so maybe - // none of all of this matters. In fact, the seed values made here could - // even be extra-special desirable if the Mersenne Twister theory says - // so-- that's why the only change I made is to restrict to odd seeds. - // - - left = -1; - - register uint32 x = (seed | 1U) & 0xFFFFFFFFU, *s = state; - register int j; - - for(left=0, *s++=x, j=N; --j; - *s++ = (x*=69069U) & 0xFFFFFFFFU); - } - - -inline uint32 eoRng::restart(void) -{ - register uint32 *p0=state, *p2=state+2, *pM=state+M, s0, s1; - register int j; - - left=N-1, next=state+1; - - for(s0=state[0], s1=state[1], j=N-M+1; --j; s0=s1, s1=*p2++) - *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); - - for(pM=state, j=M; --j; s0=s1, s1=*p2++) - *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); - - s1=state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); - s1 ^= (s1 >> 11); - s1 ^= (s1 << 7) & 0x9D2C5680U; - s1 ^= (s1 << 15) & 0xEFC60000U; - return(s1 ^ (s1 >> 18)); -} - - -inline uint32 eoRng::rand(void) - { - uint32 y; - - if(--left < 0) - return(restart()); - - y = *next++; - y ^= (y >> 11); - y ^= (y << 7) & 0x9D2C5680U; - y ^= (y << 15) & 0xEFC60000U; - return(y ^ (y >> 18)); - } - -inline double eoRng::normal(void) -{ - if (cached) - { - cached = false; - return cacheValue; - } - - float rSquare, factor, var1, var2; - - do - { - var1 = 2.0 * uniform() - 1.0; - var2 = 2.0 * uniform() - 1.0; - - rSquare = var1 * var1 + var2 * var2; - } - while (rSquare >= 1.0 || rSquare == 0.0); - - factor = sqrt(-2.0 * log(rSquare) / rSquare); - - cacheValue = var1 * factor; - cached = true; - - return (var2 * factor); -} - -#endif +/* +* Random number generator adapted from (see comments below) +* +* The random number generator is modified into a class +* by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller +* transformation to generate normal deviates. +* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es +*/ + +/* ************ DOCUMENTATION IN ORIGINAL FILE *********************/ + +// This is the ``Mersenne Twister'' random number generator MT19937, which +// generates pseudorandom integers uniformly distributed in 0..(2^32 - 1) +// starting from any odd seed in 0..(2^32 - 1). This version is a recode +// by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by +// Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in +// July-August 1997). +// +// Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha +// running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to +// generate 300 million random numbers; after recoding: 24.0 sec. for the same +// (i.e., 46.5% of original time), so speed is now about 12.5 million random +// number generations per second on this machine. +// +// According to the URL +// (and paraphrasing a bit in places), the Mersenne Twister is ``designed +// with consideration of the flaws of various existing generators,'' has +// a period of 2^19937 - 1, gives a sequence that is 623-dimensionally +// equidistributed, and ``has passed many stringent tests, including the +// die-hard test of G. Marsaglia and the load test of P. Hellekalek and +// S. Wegenkittl.'' It is efficient in memory usage (typically using 2506 +// to 5012 bytes of static data, depending on data type sizes, and the code +// is quite short as well). It generates random numbers in batches of 624 +// at a time, so the caching and pipelining of modern systems is exploited. +// It is also divide- and mod-free. +// +// This library is free software; you can redistribute it and/or modify it +// under the terms of the GNU Library General Public License as published by +// the Free Software Foundation (either version 2 of the License or, at your +// option, any later version). This library is distributed in the hope that +// it will be useful, but WITHOUT ANY WARRANTY, without even the implied +// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See +// the GNU Library General Public License for more details. You should have +// received a copy of the GNU Library General Public License along with this +// library; if not, write to the Free Software Foundation, Inc., 59 Temple +// Place, Suite 330, Boston, MA 02111-1307, USA. +// +// The code as Shawn received it included the following notice: +// +// Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When +// you use this, send an e-mail to with +// an appropriate reference to your work. +// +// It would be nice to CC: when you write. +// + +// +// uint32 must be an unsigned integer type capable of holding at least 32 +// bits; exactly 32 should be fastest, but 64 is better on an Alpha with +// GCC at -O3 optimization so try your options and see what's best for you +// + +/* ************ END DOCUMENTATION IN ORIGINAL FILE *********************/ + + +#ifndef EO_RANDOM_NUMBER_GENERATOR +#define EO_RANDOM_NUMBER_GENERATOR + +#include + +#include +#include + +// TODO: check for various compilers if this is exactly 32 bits +// Unfortunately MSVC's preprocessor does not comprehends sizeof() +// so neat preprocessing tricks will not work + +typedef unsigned long uint32; // Compiler and platform dependent! + +//----------------------------------------------------------------------------- +// eoRng +//----------------------------------------------------------------------------- +/** +eoRng is a persitent class that uses the ``Mersenne Twister'' random number generator MT19937 +for generating random numbers. The various member functions implement useful functions +for evolutionary algorithms. Included are: rand(), random(), flip() and normal(). + +Note for people porting EO to other platforms: please make sure that the typedef +uint32 in the file eoRng.h is exactly 32 bits long. It may be longer, but not +shorter. If it is longer, file compatibility between EO on different platforms +may be broken. +*/ +class eoRng : public eoObject, public eoPersistent +{ +public : + /** + ctor takes a random seed; if you want another seed, use reseed + @see reseed + */ + + eoRng(uint32 s = (uint32) time(0) ) : state(0), next(0), left(-1), cached(false), N(624), M(397), K(0x9908B0DFU) { + state = new uint32[N+1]; + initialize(s); + } + + ~eoRng(void) + { + delete [] state; + } + + /** + Re-initializes the Random Number Generator. + */ + void reseed(uint32 s) + { + initialize(s); + } + + /** + uniform(m = 1.0) returns a random double in the range [0, m) + */ + double uniform(double m = 1.0) + { // random number between [0, m] + return m * double(rand()) / double(rand_max()); + } + + /** + random() returns a random integer in the range [0, m) + */ + uint32 random(uint32 m) + { + return uint32(uniform() * double(m)); + } + + /** + flip() tosses a biased coin such that flip(x/100.0) will + returns true x% of the time + */ + bool flip(float bias) + { + return uniform() < bias; + } + + /** + normal() zero mean gaussian deviate with standard deviation of 1 + */ + double normal(void); // gaussian mutation, stdev 1 + + /** + normal(stdev) zero mean gaussian deviate with user defined standard deviation + */ + double normal(double stdev) + { + return stdev * normal(); + } + + /** + normal(mean, stdev) user defined mean gaussian deviate with user defined standard deviation + */ + double normal(double mean, double stdev) + { + return mean + normal(stdev); + } + + /** + rand() returns a random number in the range [0, rand_max) + */ + uint32 rand(); + + /** + rand_max() the maximum returned by rand() + */ + uint32 rand_max(void) const { return (uint32) 0xffffffff; } + + /** + roulette_wheel(vec, total = 0) does a roulette wheel selection + on the input vector vec. If the total is not supplied, it is + calculated. It returns an integer denoting the selected argument. + */ + template + int roulette_wheel(const std::vector& vec, T total = 0) + { + if (total == 0) + { // count + for (int i = 0; i < vec.size(); ++i) + total += vec[i]; + } + + float change = uniform() * total; + + int i = 0; + + while (change > 0) + { + change -= vec[i++]; + } + + return --i; + } + + /// + void printOn(ostream& _os) const + { + for (int i = 0; i < N; ++i) + { + _os << state[i] << ' '; + } + _os << int(next - state) << ' '; + _os << left << ' ' << cached << ' ' << cacheValue; + } + + /// + void readFrom(istream& _is) + { + for (int i = 0; i < N; ++i) + { + _is >> state[i]; + } + + int n; + _is >> n; + next = state + n; + + _is >> left; + _is >> cached; + _is >> cacheValue; + } + + +private : + uint32 restart(void); + void initialize(uint32 seed); + + uint32* state; // the array for the state + uint32* next; + int left; + + bool cached; + float cacheValue; + + const int N; + const int M; + const uint32 K; // a magic constant + + /** + Private copy ctor and assignment operator to make sure that + nobody accidentally copies the random number generator. + If you want similar RNG's, make two RNG's and initialize + them with the same seed. + */ + eoRng (const eoRng&); // no implementation + eoRng& operator=(const eoRng&); // dito +}; + +/** + The one and only global eoRng object +*/ +extern eoRng rng; + +/** + The class uniform_generator can be used in the STL generate function + to easily generate random floats and doubles between [0, _max). _max + defaults to 1.0 +*/ +template class uniform_generator +{ + public : + uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {} + + virtual T operator()(void) { return (T) uniform.uniform(maxim); } + private : + T maxim; + eoRng& uniform; +}; + +/** + The class random_generator can be used in the STL generate function + to easily generate random ints between [0, _max). +*/ +template class random_generator +{ + public : + random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {} + + virtual T operator()(void) { return (T) random.random(max); } + + private : + T maxim; + eoRng& random; +}; + +/** + The class normal_generator can be used in the STL generate function + to easily generate gaussian distributed floats and doubles. The user + can supply a standard deviation which defaults to 1. +*/ +template class normal_generator +{ + public : + normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} + + virtual T operator()(void) { return (T) normal.normal(stdev); } + + private : + T stdev; + eoRng& normal; +}; + +// Implementation of some eoRng members.... Don't mind the mess, it does work. + + +#define hiBit(u) ((u) & 0x80000000U) // mask all but highest bit of u +#define loBit(u) ((u) & 0x00000001U) // mask all but lowest bit of u +#define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u +#define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v + +inline void eoRng::initialize(uint32 seed) + { + // + // We initialize state[0..(N-1)] via the generator + // + // x_new = (69069 * x_old) mod 2^32 + // + // from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's + // _The Art of Computer Programming_, Volume 2, 3rd ed. + // + // Notes (SJC): I do not know what the initial state requirements + // of the Mersenne Twister are, but it seems this seeding generator + // could be better. It achieves the maximum period for its modulus + // (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if + // x_initial can be even, you have sequences like 0, 0, 0, ...; + // 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31, + // 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below. + // + // Even if x_initial is odd, if x_initial is 1 mod 4 then + // + // the lowest bit of x is always 1, + // the next-to-lowest bit of x is always 0, + // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , + // the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... , + // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... , + // ... + // + // and if x_initial is 3 mod 4 then + // + // the lowest bit of x is always 1, + // the next-to-lowest bit of x is always 1, + // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , + // the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... , + // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... , + // ... + // + // The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is + // 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It + // also does well in the dimension 2..5 spectral tests, but it could be + // better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth). + // + // Note that the random number user does not see the values generated + // here directly since restart() will always munge them first, so maybe + // none of all of this matters. In fact, the seed values made here could + // even be extra-special desirable if the Mersenne Twister theory says + // so-- that's why the only change I made is to restrict to odd seeds. + // + + left = -1; + + register uint32 x = (seed | 1U) & 0xFFFFFFFFU, *s = state; + register int j; + + for(left=0, *s++=x, j=N; --j; + *s++ = (x*=69069U) & 0xFFFFFFFFU); + } + + +inline uint32 eoRng::restart(void) +{ + register uint32 *p0=state, *p2=state+2, *pM=state+M, s0, s1; + register int j; + + left=N-1, next=state+1; + + for(s0=state[0], s1=state[1], j=N-M+1; --j; s0=s1, s1=*p2++) + *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); + + for(pM=state, j=M; --j; s0=s1, s1=*p2++) + *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); + + s1=state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); + s1 ^= (s1 >> 11); + s1 ^= (s1 << 7) & 0x9D2C5680U; + s1 ^= (s1 << 15) & 0xEFC60000U; + return(s1 ^ (s1 >> 18)); +} + + +inline uint32 eoRng::rand(void) + { + uint32 y; + + if(--left < 0) + return(restart()); + + y = *next++; + y ^= (y >> 11); + y ^= (y << 7) & 0x9D2C5680U; + y ^= (y << 15) & 0xEFC60000U; + return(y ^ (y >> 18)); + } + +inline double eoRng::normal(void) +{ + if (cached) + { + cached = false; + return cacheValue; + } + + float rSquare, factor, var1, var2; + + do + { + var1 = 2.0 * uniform() - 1.0; + var2 = 2.0 * uniform() - 1.0; + + rSquare = var1 * var1 + var2 * var2; + } + while (rSquare >= 1.0 || rSquare == 0.0); + + factor = sqrt(-2.0 * log(rSquare) / rSquare); + + cacheValue = var1 * factor; + cached = true; + + return (var2 * factor); +} + +#endif + diff --git a/eo/src/eoRandomIndiSelector.h b/eo/src/eoRandomIndiSelector.h index 2be2ba4c..6eceec85 100644 --- a/eo/src/eoRandomIndiSelector.h +++ b/eo/src/eoRandomIndiSelector.h @@ -1,51 +1,52 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoRandomIndiSelector.h - Selects individuals at random. - - (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ - -#ifndef eoRandomIndiSelector_h -#define eoRandomIndiSelector_h - -#include "eoIndiSelector.h" - -/** - * eoRandomSelector: just selects a random child -*/ -template -class eoRandomIndiSelector : public eoPopIndiSelector -{ - public : - - eoRandomIndiSelector(void) : eoPopIndiSelector() {} - virtual ~eoRandomIndiSelector(void) {} - - /// very complex function that returns just an individual - const EOT& do_select(void) - { - return operator[](rng.random(size())); - } - -}; - -#endif - +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoRandomIndiSelector.h + Selects individuals at random. + + (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef eoRandomIndiSelector_h +#define eoRandomIndiSelector_h + +#include "eoIndiSelector.h" + +/** + * eoRandomSelector: just selects a random child +*/ +template +class eoRandomIndiSelector : public eoPopIndiSelector +{ + public : + + eoRandomIndiSelector(void) : eoPopIndiSelector() {} + virtual ~eoRandomIndiSelector(void) {} + + /// very complex function that returns just an individual + const EOT& do_select(void) + { + return operator[](rng.random(size())); + } + +}; + +#endif + + diff --git a/eo/src/eoSequentialGOpSelector.h b/eo/src/eoSequentialGOpSelector.h index 5d899041..e702c4b8 100644 --- a/eo/src/eoSequentialGOpSelector.h +++ b/eo/src/eoSequentialGOpSelector.h @@ -1,61 +1,62 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoSequentialGOpSelector.h - Sequential Generalized Operator Selector. - - (c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es -*/ - -#ifndef eoSequentialGOpSelector_h -#define eoSequentialGOpSelector_h - -//----------------------------------------------------------------------------- - -#include "eoGOpSelector.h" -/** eoSequentialGOpSel: do proportional selection, but return a sequence of - operations to be applied one after the other. -*/ -template -class eoSequentialGOpSel : public eoGOpSelector -{ - public : - - virtual eoGeneralOp& selectOp() - { - combined.clear(); - - for (int i = 0; i < size(); ++i) - { - if (operator[](i) == 0) - continue; - - if (rng.flip(getRates()[i])) - combined.addOp(operator[](i)); - } - - return combined; - } - - private : - - eoCombinedOp combined; -}; - -#endif +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSequentialGOpSelector.h + Sequential Generalized Operator Selector. + + (c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es +*/ + +#ifndef eoSequentialGOpSelector_h +#define eoSequentialGOpSelector_h + +//----------------------------------------------------------------------------- + +#include "eoGOpSelector.h" +/** eoSequentialGOpSel: do proportional selection, but return a sequence of + operations to be applied one after the other. +*/ +template +class eoSequentialGOpSel : public eoGOpSelector +{ + public : + + virtual eoGeneralOp& selectOp() + { + combined.clear(); + + for (int i = 0; i < size(); ++i) + { + if (operator[](i) == 0) + continue; + + if (rng.flip(getRates()[i])) + combined.addOp(operator[](i)); + } + + return combined; + } + + private : + + eoCombinedOp combined; +}; + +#endif + diff --git a/eo/src/eoSteadyStateEA.h b/eo/src/eoSteadyStateEA.h index 6a0b5abf..824c67a7 100644 --- a/eo/src/eoSteadyStateEA.h +++ b/eo/src/eoSteadyStateEA.h @@ -1,86 +1,87 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoSteadyStateEA.h -// (c) GeNeura Team, 2000 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _eoSteadyStateEA_h -#define _eoSteadyStateEA_h - -//----------------------------------------------------------------------------- - -#include "eoSteadyStateGeneration.h" // eoPop -#include - -/** EOSteadyStateEA: - An easy-to-use evolutionary algorithm, just supply - a general operator selector, a selector for choosing the ones - to reproduce and an eoSteadyStateInserter that takes care of evaluating - and inserter the guy/girl in the steady state population. -*/ -template class eoSteadyStateEA: public eoAlgo -{ - public: - /// Constructor. - eoSteadyStateEA( - eoGOpSelector& _opSelector, - eoPopIndiSelector& _selector, - eoSteadyStateInserter& _inserter, - eoTerm& _terminator, - unsigned _steps = 0 ) - : step(_opSelector, _selector, _inserter), - terminator( _terminator) - {}; - - /// Constructor from an already created generation - eoSteadyStateEA(eoSteadyStateGeneration& _gen, - eoTerm& _terminator): - step(_gen), - terminator( _terminator){}; - - /// Apply one generation of evolution to the population. - virtual void operator()(eoPop& pop) { - do { - try - { - step(pop); - } - catch (exception& e) - { - string s = e.what(); - s.append( " in eoSteadyStateEA "); - throw runtime_error( s ); - } - } while ( terminator( pop ) ); - - } - - /// Class name. - string className() const { return "eoSteadyStateEA"; } - - private: - eoSteadyStateGeneration step; - eoTerm& terminator; -}; - -//----------------------------------------------------------------------------- - -#endif eoEasyEA_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSteadyStateEA.h +// (c) GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSteadyStateEA_h +#define _eoSteadyStateEA_h + +//----------------------------------------------------------------------------- + +#include "eoSteadyStateGeneration.h" // eoPop +#include + +/** EOSteadyStateEA: + An easy-to-use evolutionary algorithm, just supply + a general operator selector, a selector for choosing the ones + to reproduce and an eoSteadyStateInserter that takes care of evaluating + and inserter the guy/girl in the steady state population. +*/ +template class eoSteadyStateEA: public eoAlgo +{ + public: + /// Constructor. + eoSteadyStateEA( + eoGOpSelector& _opSelector, + eoPopIndiSelector& _selector, + eoSteadyStateInserter& _inserter, + eoTerm& _terminator, + unsigned _steps = 0 ) + : step(_opSelector, _selector, _inserter), + terminator( _terminator) + {}; + + /// Constructor from an already created generation + eoSteadyStateEA(eoSteadyStateGeneration& _gen, + eoTerm& _terminator): + step(_gen), + terminator( _terminator){}; + + /// Apply one generation of evolution to the population. + virtual void operator()(eoPop& pop) { + do { + try + { + step(pop); + } + catch (exception& e) + { + string s = e.what(); + s.append( " in eoSteadyStateEA "); + throw runtime_error( s ); + } + } while ( terminator( pop ) ); + + } + + /// Class name. + string className() const { return "eoSteadyStateEA"; } + + private: + eoSteadyStateGeneration step; + eoTerm& terminator; +}; + +//----------------------------------------------------------------------------- + +#endif eoEasyEA_h + diff --git a/eo/src/eoSteadyStateGeneration.h b/eo/src/eoSteadyStateGeneration.h index 1c1aeebc..c055b107 100644 --- a/eo/src/eoSteadyStateGeneration.h +++ b/eo/src/eoSteadyStateGeneration.h @@ -1,88 +1,89 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoSteadyStateGeneration.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef eoSteadyStateGeneration_h -#define eoSteadyStateGeneration_h - -//----------------------------------------------------------------------------- - -#include // eoPop -#include -#include // eoSelect, eoTranform, eoMerge - -#include "eoGOpSelector.h" -#include "eoIndiSelector.h" -#include "eoSteadyStateInserter.h" - -//----------------------------------------------------------------------------- - -/** eoSteadyStateGeneration - * Single step of a steady state evolutionary algorithm. - * Proceeds by updating one individual at a time, by first selecting parents, - * creating one or more children and subsequently overwrite (a) bad individual(s) -*/ -template class eoSteadyStateGeneration: public eoAlgo -{ - public: - /// Constructor. - eoSteadyStateGeneration( - eoGOpSelector& _opSelector, - eoPopIndiSelector& _selector, - eoSteadyStateInserter& _inserter, - unsigned _steps = 0) : - opSelector(_opSelector), - selector(_selector), - inserter(_inserter) , - steps(_steps) {}; - - - /// Apply one generation of evolution to the population. - virtual void operator()(eoPop& pop) - { - unsigned nSteps = steps; - if (nSteps == 0) - { - nSteps = pop.size(); // make a 'generation equivalent' - } - - for (unsigned i = 0; i < nSteps; ++i) - { - opSelector.selectOp()(selector(pop), inserter(pop)); - } - - } - - /// Class name. - string className() const { return "eoSteadyStateGeneration"; } - - private: - eoGOpSelector& opSelector; - eoPopIndiSelector& selector; - eoSteadyStateInserter& inserter; - unsigned steps; -}; - -//----------------------------------------------------------------------------- - -#endif eoGeneration_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSteadyStateGeneration.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoSteadyStateGeneration_h +#define eoSteadyStateGeneration_h + +//----------------------------------------------------------------------------- + +#include // eoPop +#include +#include // eoSelect, eoTranform, eoMerge + +#include "eoGOpSelector.h" +#include "eoIndiSelector.h" +#include "eoSteadyStateInserter.h" + +//----------------------------------------------------------------------------- + +/** eoSteadyStateGeneration + * Single step of a steady state evolutionary algorithm. + * Proceeds by updating one individual at a time, by first selecting parents, + * creating one or more children and subsequently overwrite (a) bad individual(s) +*/ +template class eoSteadyStateGeneration: public eoAlgo +{ + public: + /// Constructor. + eoSteadyStateGeneration( + eoGOpSelector& _opSelector, + eoPopIndiSelector& _selector, + eoSteadyStateInserter& _inserter, + unsigned _steps = 0) : + opSelector(_opSelector), + selector(_selector), + inserter(_inserter) , + steps(_steps) {}; + + + /// Apply one generation of evolution to the population. + virtual void operator()(eoPop& pop) + { + unsigned nSteps = steps; + if (nSteps == 0) + { + nSteps = pop.size(); // make a 'generation equivalent' + } + + for (unsigned i = 0; i < nSteps; ++i) + { + opSelector.selectOp()(selector(pop), inserter(pop)); + } + + } + + /// Class name. + string className() const { return "eoSteadyStateGeneration"; } + + private: + eoGOpSelector& opSelector; + eoPopIndiSelector& selector; + eoSteadyStateInserter& inserter; + unsigned steps; +}; + +//----------------------------------------------------------------------------- + +#endif eoGeneration_h + diff --git a/eo/src/eoSteadyStateInserter.h b/eo/src/eoSteadyStateInserter.h index 26f299f7..d2264294 100644 --- a/eo/src/eoSteadyStateInserter.h +++ b/eo/src/eoSteadyStateInserter.h @@ -1,51 +1,51 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoSteadyStateInserter.h - Still abstract population insertion operator that is initialized with - and eoEvalFunc object to be able to evaluate individuals before inserting - them. - - (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ - -#ifndef eoSteadyStateInserter_h -#define eoSteadyStateInserter_h - - -#include "eoEvalFunc.h" - -/** - * eoSteadyStateInserter: Interface class that enables an operator to update - * a population with a new individual... it contains an eoEvalFunc object to - * make sure that every individual is evaluated before it is inserted -*/ -template -class eoSteadyStateInserter : public eoPopInserter -{ - public : - eoSteadyStateInserter(eoEvalFunc& _eval) : eval(_eval) , eoPopInserter() {} - - protected : - - eoEvalFunc& eval; -}; - - -#endif \ No newline at end of file +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSteadyStateInserter.h + Still abstract population insertion operator that is initialized with + and eoEvalFunc object to be able to evaluate individuals before inserting + them. + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef eoSteadyStateInserter_h +#define eoSteadyStateInserter_h + + +#include "eoEvalFunc.h" + +/** + * eoSteadyStateInserter: Interface class that enables an operator to update + * a population with a new individual... it contains an eoEvalFunc object to + * make sure that every individual is evaluated before it is inserted +*/ +template +class eoSteadyStateInserter : public eoPopInserter +{ + public : + eoSteadyStateInserter(eoEvalFunc& _eval) : eval(_eval) , eoPopInserter() {} + + protected : + + eoEvalFunc& eval; +}; + + +#endif diff --git a/eo/src/eoStochTournament.h b/eo/src/eoStochTournament.h index afc05d74..8a677262 100644 --- a/eo/src/eoStochTournament.h +++ b/eo/src/eoStochTournament.h @@ -1,68 +1,69 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoStochTournament.h -// (c) GeNeura Team, 1998 - EEAAX 1999 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - Marc.Schoenauer@polytechnique.fr - */ -//----------------------------------------------------------------------------- - -#ifndef eoStochTournament_h -#define eoStochTournament_h - -//----------------------------------------------------------------------------- - -#include // -#include // accumulate -#include // eoPop eoSelect MINFLOAT -#include - -//----------------------------------------------------------------------------- -/** eoStochTournament: a selection method that selects ONE individual by - binary stochastic tournament - -MS- 24/10/99 */ -//----------------------------------------------------------------------------- - -template class eoStochTournament: public eoSelectOne -{ - public: - - /// - eoStochTournament(float _Trate = 1.0 ):eoSelectOne(), Trate(_Trate) { - // consistency check - if (Trate < 0.5) { - cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n"; - Trate = 0.55; - } - } - - /** DANGER: if you want to be able to minimize as well as maximizem - DON'T cast the fitness to a float, use the EOT comparator! */ - virtual const EOT& operator()(const eoPop& pop) - { - return stochastic_tournament(pop, Trate)(); - } - -private: - float Trate; -}; - -//----------------------------------------------------------------------------- - -#endif eoDetTournament_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoStochTournament.h +// (c) GeNeura Team, 1998 - EEAAX 1999 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef eoStochTournament_h +#define eoStochTournament_h + +//----------------------------------------------------------------------------- + +#include // +#include // accumulate +#include // eoPop eoSelect MINFLOAT +#include + +//----------------------------------------------------------------------------- +/** eoStochTournament: a selection method that selects ONE individual by + binary stochastic tournament + -MS- 24/10/99 */ +//----------------------------------------------------------------------------- + +template class eoStochTournament: public eoSelectOne +{ + public: + + /// + eoStochTournament(float _Trate = 1.0 ):eoSelectOne(), Trate(_Trate) { + // consistency check + if (Trate < 0.5) { + cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n"; + Trate = 0.55; + } + } + + /** DANGER: if you want to be able to minimize as well as maximizem + DON'T cast the fitness to a float, use the EOT comparator! */ + virtual const EOT& operator()(const eoPop& pop) + { + return stochastic_tournament(pop, Trate)(); + } + +private: + float Trate; +}; + +//----------------------------------------------------------------------------- + +#endif eoDetTournament_h + diff --git a/eo/src/eoStochTournamentInserter.h b/eo/src/eoStochTournamentInserter.h index f91b546f..56bb8e70 100644 --- a/eo/src/eoStochTournamentInserter.h +++ b/eo/src/eoStochTournamentInserter.h @@ -1,73 +1,73 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoStochTournamentInserter.h - Concrete steady state inserter. It is initialized with a population and - inserts individuals in the population based on an inverse stochastic - tournament - - (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ - -#ifndef eoStochTournamentInserter_h -#define eoStochTournamentInserter_h - - -#include "eoSteadyStateInserter.h" -#include "selectors.h" - -/** - * eoDetTournamentInserter: Uses an inverse stochastic tournament to figure - * out who gets overridden by the new individual. It resets the fitness of the - * individual. -*/ -template -class eoStochTournamentInserter : public eoSteadyStateInserter -{ - public : - - eoStochTournamentInserter(eoEvalFunc& _eval, double _t_rate) : t_rate(_t_rate), eoSteadyStateInserter(_eval) - { - if (t_rate < 0.5) - { // warning, error? - t_rate = 0.55; - } - - if (t_rate >= 1.0) - { - t_rate = 0.99; // 1.0 would mean deterministic tournament - } - } - - void insert(const EOT& _eot) - { - EOT& eo = inverse_stochastic_tournament(pop(), t_rate); - eo = _eot; // overwrite loser of tournament - - eo.invalidate(); - eval(eo); // Evaluate after insert - } - - string className(void) const { return "eoStochTournamentInserter"; } - - private : - double t_rate; -}; - -#endif \ No newline at end of file +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoStochTournamentInserter.h + Concrete steady state inserter. It is initialized with a population and + inserts individuals in the population based on an inverse stochastic + tournament + + (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef eoStochTournamentInserter_h +#define eoStochTournamentInserter_h + + +#include "eoSteadyStateInserter.h" +#include "selectors.h" + +/** + * eoDetTournamentInserter: Uses an inverse stochastic tournament to figure + * out who gets overridden by the new individual. It resets the fitness of the + * individual. +*/ +template +class eoStochTournamentInserter : public eoSteadyStateInserter +{ + public : + + eoStochTournamentInserter(eoEvalFunc& _eval, double _t_rate) : t_rate(_t_rate), eoSteadyStateInserter(_eval) + { + if (t_rate < 0.5) + { // warning, error? + t_rate = 0.55; + } + + if (t_rate >= 1.0) + { + t_rate = 0.99; // 1.0 would mean deterministic tournament + } + } + + void insert(const EOT& _eot) + { + EOT& eo = inverse_stochastic_tournament(pop(), t_rate); + eo = _eot; // overwrite loser of tournament + + eo.invalidate(); + eval(eo); // Evaluate after insert + } + + string className(void) const { return "eoStochTournamentInserter"; } + + private : + double t_rate; +}; + +#endif diff --git a/eo/src/eoString.h b/eo/src/eoString.h index ff515c70..d1ba55b4 100644 --- a/eo/src/eoString.h +++ b/eo/src/eoString.h @@ -1,147 +1,148 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoString.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _eoString_H -#define _eoString_H - -// STL libraries -#include -#include - -using namespace std; - -// EO headers -#include - -//----------------------------------------------------------------------------- -// eoString -//----------------------------------------------------------------------------- - -/** Adaptor that turns an STL string into an EO */ -template -class eoString: public eo1d, public string { -public: - - /// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator - //@{ - /// ctor - eoString( const string& _str ="" ) - : eo1d(), string( _str ) {}; - - - /** Ctor using a random number generator - @param _size Lineal length of the object - @param _rnd a random number generator, which returns a random value each time it´s called - */ - eoString( unsigned _size, eoRnd& _rnd ) - : eo1d(), string(){ - for ( unsigned i = 0; i < _size; i ++ ) { - *this += _rnd(); - } - }; +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoString.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoString_H +#define _eoString_H + +// STL libraries +#include +#include + +using namespace std; + +// EO headers +#include + +//----------------------------------------------------------------------------- +// eoString +//----------------------------------------------------------------------------- + +/** Adaptor that turns an STL string into an EO */ +template +class eoString: public eo1d, public string { +public: + + /// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator + //@{ + /// ctor + eoString( const string& _str ="" ) + : eo1d(), string( _str ) {}; + + + /** Ctor using a random number generator + @param _size Lineal length of the object + @param _rnd a random number generator, which returns a random value each time it´s called + */ + eoString( unsigned _size, eoRnd& _rnd ) + : eo1d(), string(){ + for ( unsigned i = 0; i < _size; i ++ ) { + *this += _rnd(); + } + }; /** Ctor from a stream @param _s input stream - */ + */ eoString( istream & _s ) : eo1d(){ _s >> *this; }; - - /// copy ctor - eoString( const eoString& _eoStr ) - :eo1d( static_cast & > ( _eoStr ) ), - string( _eoStr ){}; - - /// Assignment operator - const eoString& operator =( const eoString& _eoStr ) { - if ( this != & _eoStr ) { - eo1d::operator = ( _eoStr ); - string::operator = ( _eoStr ); - } - return *this; - } - - /// dtor - virtual ~eoString() {}; -//@} - - - /** methods that implement the eo1d protocol - @exception out_of_range if _i is larger than EO´s size - */ - virtual char getGene( unsigned _i ) const { - if ( _i >= length() ) - throw out_of_range( "out_of_range when reading gene"); - return (*this)[_i]; - }; - - /** methods that implement the eo1d protocol - @exception out_of_range if _i is larger than EO´s size - */ - virtual void setGene( unsigned _i, const char& _value ) { - if ( _i >= size() ) - throw out_of_range( "out_of_range when writing a gene"); - (*this)[_i] = _value; - }; - - /** Inserts a value after _i, displacing anything to the right - @exception out_of_range if _i is larger than EO´s size - */ - virtual void insertGene( unsigned _i, char _val ) { - if (_i <= this->size() ) { - string::iterator i = this->begin()+_i; - this->insert( i, _val ); - } else - throw out_of_range( "out_of_range when inserting gene"); - }; - - /** Eliminates the gene at position _i - @exception out_of_range if _i is larger than EO´s size - */ - virtual void deleteGene( unsigned _i ) { - if (_i < this->size() ) { - string::iterator i = this->begin()+_i; - this->erase( i ); - } else - throw out_of_range( "out_of_range when deleting gene"); - }; - - /// methods that implement the EO protocol - virtual unsigned length() const { return this->size(); }; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eo1d - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoString";}; - //@} - - -}; - -#endif + + /// copy ctor + eoString( const eoString& _eoStr ) + :eo1d( static_cast & > ( _eoStr ) ), + string( _eoStr ){}; + + /// Assignment operator + const eoString& operator =( const eoString& _eoStr ) { + if ( this != & _eoStr ) { + eo1d::operator = ( _eoStr ); + string::operator = ( _eoStr ); + } + return *this; + } + + /// dtor + virtual ~eoString() {}; +//@} + + + /** methods that implement the eo1d protocol + @exception out_of_range if _i is larger than EO´s size + */ + virtual char getGene( unsigned _i ) const { + if ( _i >= length() ) + throw out_of_range( "out_of_range when reading gene"); + return (*this)[_i]; + }; + + /** methods that implement the eo1d protocol + @exception out_of_range if _i is larger than EO´s size + */ + virtual void setGene( unsigned _i, const char& _value ) { + if ( _i >= size() ) + throw out_of_range( "out_of_range when writing a gene"); + (*this)[_i] = _value; + }; + + /** Inserts a value after _i, displacing anything to the right + @exception out_of_range if _i is larger than EO´s size + */ + virtual void insertGene( unsigned _i, char _val ) { + if (_i <= this->size() ) { + string::iterator i = this->begin()+_i; + this->insert( i, _val ); + } else + throw out_of_range( "out_of_range when inserting gene"); + }; + + /** Eliminates the gene at position _i + @exception out_of_range if _i is larger than EO´s size + */ + virtual void deleteGene( unsigned _i ) { + if (_i < this->size() ) { + string::iterator i = this->begin()+_i; + this->erase( i ); + } else + throw out_of_range( "out_of_range when deleting gene"); + }; + + /// methods that implement the EO protocol + virtual unsigned length() const { return this->size(); }; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eo1d + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoString";}; + //@} + + +}; + +#endif + diff --git a/eo/src/eoTranspose.h b/eo/src/eoTranspose.h index a46b8328..79146743 100644 --- a/eo/src/eoTranspose.h +++ b/eo/src/eoTranspose.h @@ -1,91 +1,92 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoTranspose.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EOTRANSPOSE_h -#define _EOTRANSPOSE_h - -#include - -#include - -/** Transposition operator: interchanges the position of two genes -of an EO. These positions must be defined by an only index, that is, -EOT must subclass eo1d -*/ -template -class eoTranspose: public eoMonOp { -public: - /// - eoTranspose() - : eoMonOp< EOT >( ){}; - - /// needed virtual dtor - virtual ~eoTranspose() {}; - - /// - virtual void operator()( EOT& _eo ) const { - eoUniform uniform(0, _eo.length() ); - unsigned pos1 = uniform(), - pos2 = uniform(); - applyAt( _eo, pos1, pos2 ); - } - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoOp - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoTranspose";}; - //@} - -private: - -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - /** applies operator to one gene in the EO - @param _eo victim of transposition - @param i, j positions of the genes that are going to be changed - @throw runtime_exception if the positions to write are incorrect - */ - virtual void applyAt( EOT& _eo, unsigned _i, unsigned _j) const { - try { - Type tmp = _eo.gene( _i ); - _eo.gene( _i ) = _eo.gene( _j ); - _eo.gene( _j ) = tmp; - } catch ( exception& _e ) { - string msg = _e.what(); - msg += "Caught exception at eoTranspose"; - throw runtime_error( msg.c_str() ); - } - } - -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoTranspose.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOTRANSPOSE_h +#define _EOTRANSPOSE_h + +#include + +#include + +/** Transposition operator: interchanges the position of two genes +of an EO. These positions must be defined by an only index, that is, +EOT must subclass eo1d +*/ +template +class eoTranspose: public eoMonOp { +public: + /// + eoTranspose() + : eoMonOp< EOT >( ){}; + + /// needed virtual dtor + virtual ~eoTranspose() {}; + + /// + virtual void operator()( EOT& _eo ) const { + eoUniform uniform(0, _eo.length() ); + unsigned pos1 = uniform(), + pos2 = uniform(); + applyAt( _eo, pos1, pos2 ); + } + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoOp + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoTranspose";}; + //@} + +private: + +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + /** applies operator to one gene in the EO + @param _eo victim of transposition + @param i, j positions of the genes that are going to be changed + @throw runtime_exception if the positions to write are incorrect + */ + virtual void applyAt( EOT& _eo, unsigned _i, unsigned _j) const { + try { + Type tmp = _eo.gene( _i ); + _eo.gene( _i ) = _eo.gene( _j ); + _eo.gene( _j ) = tmp; + } catch ( exception& _e ) { + string msg = _e.what(); + msg += "Caught exception at eoTranspose"; + throw runtime_error( msg.c_str() ); + } + } + +}; + +#endif + diff --git a/eo/src/eoUniformSelect.h b/eo/src/eoUniformSelect.h index 74775aab..ab65a7f3 100644 --- a/eo/src/eoUniformSelect.h +++ b/eo/src/eoUniformSelect.h @@ -1,64 +1,65 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoUniformSelect.h -// (c) GeNeura Team, 1998 - EEAAX 1999 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - Marc.Schoenauer@polytechnique.fr - */ -//----------------------------------------------------------------------------- - -#ifndef eoUniformSelect_h -#define eoUniformSelect_h -// WARNING: 2 classes in this one - eoUniformSelect and eoCopySelect - -//----------------------------------------------------------------------------- - -#include // -#include // accumulate -#include // eoPop eoSelect MINFLOAT -#include - -//----------------------------------------------------------------------------- -/** eoUniformSelect: a selection method that selects ONE individual randomly - -MS- 22/10/99 */ -//----------------------------------------------------------------------------- - -template class eoUniformSelect: public eoSelectOne -{ - public: - /// (Default) Constructor. - eoUniformSelect():eoSelectOne() {} - - /// not a big deal!!! - virtual const EOT& operator()(const eoPop& pop) { - return pop[rng.random(pop.size())] ; - } - - /// Methods inherited from eoObject - //@{ - - /** Return the class id. - * @return the class name as a string - */ - virtual string className() const { return "eoUniformSelect"; }; - - private: -}; - -#endif eoUniformSelect_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoUniformSelect.h +// (c) GeNeura Team, 1998 - EEAAX 1999 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef eoUniformSelect_h +#define eoUniformSelect_h +// WARNING: 2 classes in this one - eoUniformSelect and eoCopySelect + +//----------------------------------------------------------------------------- + +#include // +#include // accumulate +#include // eoPop eoSelect MINFLOAT +#include + +//----------------------------------------------------------------------------- +/** eoUniformSelect: a selection method that selects ONE individual randomly + -MS- 22/10/99 */ +//----------------------------------------------------------------------------- + +template class eoUniformSelect: public eoSelectOne +{ + public: + /// (Default) Constructor. + eoUniformSelect():eoSelectOne() {} + + /// not a big deal!!! + virtual const EOT& operator()(const eoPop& pop) { + return pop[rng.random(pop.size())] ; + } + + /// Methods inherited from eoObject + //@{ + + /** Return the class id. + * @return the class name as a string + */ + virtual string className() const { return "eoUniformSelect"; }; + + private: +}; + +#endif eoUniformSelect_h + diff --git a/eo/src/eoWrappedOps.h b/eo/src/eoWrappedOps.h index 2e226182..10e4fb36 100644 --- a/eo/src/eoWrappedOps.h +++ b/eo/src/eoWrappedOps.h @@ -1,220 +1,221 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - eoWrappedOps.h - Derived from the General genetic operator, which can be used to wrap any unary or binary - operator. File also contains the eoCombinedOp, needed by the eoSequentialGOpSelector - - (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ - -//----------------------------------------------------------------------------- - -#ifndef eoWrappedOps_h -#define eoWrappedOps_h - -//----------------------------------------------------------------------------- - -#include // eoOp, eoMonOp, eoBinOp -#include "eoRNG.h" - -using namespace std; - -/// Wraps monary operators -template -class eoWrappedMonOp : public eoGeneralOp -{ -public : - /// - eoWrappedMonOp(const eoMonOp& _op) : eoGeneralOp(), op(_op) {}; - - /// - virtual ~eoWrappedMonOp() {} - - /// Instantiates the abstract method - void operator()( eoIndiSelector& _in, - eoInserter& _out) const { - EOT result = _in.select(); - op( result ); - _out.insert(result); - } - - /// - virtual string className() const {return "eoWrappedMonOp";}; - - -private : - const eoMonOp& op; -}; - - -/// Wraps binary operators -template -class eoWrappedBinOp : public eoGeneralOp -{ -public : - /// - eoWrappedBinOp(const eoBinOp& _op) : eoGeneralOp(), op(_op) {} - - /// - virtual ~eoWrappedBinOp() {} - - /// Instantiates the abstract method. EOT should have copy ctor. - void operator()(eoIndiSelector& _in, - eoInserter& _out) const { - EOT out1 = _in.select(); - const EOT& out2 = _in.select(); - op(out1, out2); - _out.insert(out1); - } - - /// - virtual string className() const {return "eoWrappedBinOp";}; - -private : - const eoBinOp& op; -}; - -/// Wraps Quadratic operators -template -class eoWrappedQuadraticOp : public eoGeneralOp -{ -public : - /// - eoWrappedQuadraticOp(const eoQuadraticOp& _op) : eoGeneralOp(), op(_op) {} - - /// - virtual ~eoWrappedQuadraticOp() {} - - /// Instantiates the abstract method. EOT should have copy ctor. - void operator()(eoIndiSelector& _in, - eoInserter& _out) const { - EOT out1 = _in.select(); - EOT out2 = _in.select(); - op(out1, out2); - _out.insert(out1); - _out.insert(out2); - } - - /// - virtual string className() const {return "eoWrappedQuadraticOp";}; - -private : - const eoQuadraticOp& op; -}; - -/// Combines several ops -template -class eoCombinedOp : public eoGeneralOp -{ -public : - - /// - eoCombinedOp() : eoGeneralOp() {} - - /// - virtual ~eoCombinedOp() {} - - /// Adds a new operator to the combined Op - void addOp(eoGeneralOp* _op) - { - ops.push_back(_op); - } - - - /// Erases all operators added so far - void clear(void) { - ops.resize(0); - } - - /// Helper class to make sure that stuff that is inserted will be used again with the next operator - class eoIndiSelectorInserter : public eoIndiSelector, public eoInserter - { - public : - eoIndiSelectorInserter(eoIndiSelector& _in) - : eoIndiSelector(), eoInserter(), in(_in) - {} - - size_t size() const { return in.size(); } - const EOT& operator[](size_t _n) const { return in[_n]; } - - const EOT& select(void) - { - if (results.empty()) - { - return in.select(); - } - // else we use the previously inserted individual, - // an iterator to it is stored in 'results', but the memory - // is kept by 'intermediate'. - - list::iterator it = *results.begin(); - results.pop_front(); - return *it; - } - - void insert(const EOT& _eot) - { - intermediate.push_front(_eot); - results.push_front(intermediate.begin()); - } - - void fill(eoInserter& _out) - { - typedef list::iterator>::iterator Iterator; - - for (Iterator it = results.begin(); it != results.end(); ++it) - { - _out.insert(**it); - } - - results.clear(); - intermediate.clear(); // reclaim memory - } - - private : - - eoIndiSelector& in; - - // using lists as we need to push and pop a lot - // 'results' are iterators to the contents of 'intermediate' - // to prevent copying to and from intermediate... - list::iterator> results; - list intermediate; - }; - - /// Applies all ops in the combined op - void operator()( eoIndiSelector& _in, - eoInserter& _out ) const { - - eoIndiSelectorInserter in_out(_in); - - for (size_t i = 0; i < ops.size(); ++i) - { - (*ops[i])(in_out, in_out); - } - - in_out.fill(_out); - } - -private : - vector* > ops; -}; - -#endif eoGeneral_h +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoWrappedOps.h + Derived from the General genetic operator, which can be used to wrap any unary or binary + operator. File also contains the eoCombinedOp, needed by the eoSequentialGOpSelector + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +//----------------------------------------------------------------------------- + +#ifndef eoWrappedOps_h +#define eoWrappedOps_h + +//----------------------------------------------------------------------------- + +#include // eoOp, eoMonOp, eoBinOp +#include "eoRNG.h" + +using namespace std; + +/// Wraps monary operators +template +class eoWrappedMonOp : public eoGeneralOp +{ +public : + /// + eoWrappedMonOp(const eoMonOp& _op) : eoGeneralOp(), op(_op) {}; + + /// + virtual ~eoWrappedMonOp() {} + + /// Instantiates the abstract method + void operator()( eoIndiSelector& _in, + eoInserter& _out) const { + EOT result = _in.select(); + op( result ); + _out.insert(result); + } + + /// + virtual string className() const {return "eoWrappedMonOp";}; + + +private : + const eoMonOp& op; +}; + + +/// Wraps binary operators +template +class eoWrappedBinOp : public eoGeneralOp +{ +public : + /// + eoWrappedBinOp(const eoBinOp& _op) : eoGeneralOp(), op(_op) {} + + /// + virtual ~eoWrappedBinOp() {} + + /// Instantiates the abstract method. EOT should have copy ctor. + void operator()(eoIndiSelector& _in, + eoInserter& _out) const { + EOT out1 = _in.select(); + const EOT& out2 = _in.select(); + op(out1, out2); + _out.insert(out1); + } + + /// + virtual string className() const {return "eoWrappedBinOp";}; + +private : + const eoBinOp& op; +}; + +/// Wraps Quadratic operators +template +class eoWrappedQuadraticOp : public eoGeneralOp +{ +public : + /// + eoWrappedQuadraticOp(const eoQuadraticOp& _op) : eoGeneralOp(), op(_op) {} + + /// + virtual ~eoWrappedQuadraticOp() {} + + /// Instantiates the abstract method. EOT should have copy ctor. + void operator()(eoIndiSelector& _in, + eoInserter& _out) const { + EOT out1 = _in.select(); + EOT out2 = _in.select(); + op(out1, out2); + _out.insert(out1); + _out.insert(out2); + } + + /// + virtual string className() const {return "eoWrappedQuadraticOp";}; + +private : + const eoQuadraticOp& op; +}; + +/// Combines several ops +template +class eoCombinedOp : public eoGeneralOp +{ +public : + + /// + eoCombinedOp() : eoGeneralOp() {} + + /// + virtual ~eoCombinedOp() {} + + /// Adds a new operator to the combined Op + void addOp(eoGeneralOp* _op) + { + ops.push_back(_op); + } + + + /// Erases all operators added so far + void clear(void) { + ops.resize(0); + } + + /// Helper class to make sure that stuff that is inserted will be used again with the next operator + class eoIndiSelectorInserter : public eoIndiSelector, public eoInserter + { + public : + eoIndiSelectorInserter(eoIndiSelector& _in) + : eoIndiSelector(), eoInserter(), in(_in) + {} + + size_t size() const { return in.size(); } + const EOT& operator[](size_t _n) const { return in[_n]; } + + const EOT& select(void) + { + if (results.empty()) + { + return in.select(); + } + // else we use the previously inserted individual, + // an iterator to it is stored in 'results', but the memory + // is kept by 'intermediate'. + + list::iterator it = *results.begin(); + results.pop_front(); + return *it; + } + + void insert(const EOT& _eot) + { + intermediate.push_front(_eot); + results.push_front(intermediate.begin()); + } + + void fill(eoInserter& _out) + { + typedef list::iterator>::iterator Iterator; + + for (Iterator it = results.begin(); it != results.end(); ++it) + { + _out.insert(**it); + } + + results.clear(); + intermediate.clear(); // reclaim memory + } + + private : + + eoIndiSelector& in; + + // using lists as we need to push and pop a lot + // 'results' are iterators to the contents of 'intermediate' + // to prevent copying to and from intermediate... + list::iterator> results; + list intermediate; + }; + + /// Applies all ops in the combined op + void operator()( eoIndiSelector& _in, + eoInserter& _out ) const { + + eoIndiSelectorInserter in_out(_in); + + for (size_t i = 0; i < ops.size(); ++i) + { + (*ops[i])(in_out, in_out); + } + + in_out.fill(_out); + } + +private : + vector* > ops; +}; + +#endif eoGeneral_h + diff --git a/eo/src/eoXOver2.h b/eo/src/eoXOver2.h index ec67c399..867de1c0 100644 --- a/eo/src/eoXOver2.h +++ b/eo/src/eoXOver2.h @@ -1,106 +1,107 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoXOver2.h -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- - -#ifndef _EOXOVER2_h -#define _EOXOVER2_h - - -// for swap -#if defined( __BORLANDC__ ) -#include -#else -#include -#endif - -// EO includes -#include -#include - -/** 2-point crossover: takes the genes in the central section of two EOs -and interchanges it -*/ -template -class eoXOver2: public eoQuadraticOp { -public: - /// - eoXOver2() - : eoQuadraticOp< EOT >(){}; - - /// - virtual ~eoXOver2() {}; - - /// - virtual void operator()( EOT& _eo1, - EOT& _eo2 ) const { - unsigned len1 = _eo1.length(), len2 = _eo2.length(), - len= (len1 > len2)?len2:len1; - eoUniform uniform( 0, len ); - unsigned pos1 = uniform(), pos2 = uniform() ; - - applyAt( _eo1, _eo2, pos1, pos2 ); - - } - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoOp - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoXOver2";}; - //@} - -private: - -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - /// applies operator to one gene in the EO - virtual void applyAt( EOT& _eo, EOT& _eo2, - unsigned _i, unsigned _j = 0) const { - - if ( _j < _i ) - swap( _i, _j ); - - unsigned len1 = _eo.length(), len2 = _eo2.length(), - len= (len1 > len2)?len2:len1; - - if ( (_j > len) || (_i> len ) ) - throw runtime_error( "xOver2: applying xOver past boundaries"); - - for ( unsigned i = _i; i < _j; i++ ) { - Type tmp = _eo.gene( i ); - _eo.gene( i ) = _eo2.gene( i ); - _eo2.gene( i ) = tmp ; - } - - } - -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoXOver2.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _EOXOVER2_h +#define _EOXOVER2_h + + +// for swap +#if defined( __BORLANDC__ ) +#include +#else +#include +#endif + +// EO includes +#include +#include + +/** 2-point crossover: takes the genes in the central section of two EOs +and interchanges it +*/ +template +class eoXOver2: public eoQuadraticOp { +public: + /// + eoXOver2() + : eoQuadraticOp< EOT >(){}; + + /// + virtual ~eoXOver2() {}; + + /// + virtual void operator()( EOT& _eo1, + EOT& _eo2 ) const { + unsigned len1 = _eo1.length(), len2 = _eo2.length(), + len= (len1 > len2)?len2:len1; + eoUniform uniform( 0, len ); + unsigned pos1 = uniform(), pos2 = uniform() ; + + applyAt( _eo1, _eo2, pos1, pos2 ); + + } + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoOp + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoXOver2";}; + //@} + +private: + +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + /// applies operator to one gene in the EO + virtual void applyAt( EOT& _eo, EOT& _eo2, + unsigned _i, unsigned _j = 0) const { + + if ( _j < _i ) + swap( _i, _j ); + + unsigned len1 = _eo.length(), len2 = _eo2.length(), + len= (len1 > len2)?len2:len1; + + if ( (_j > len) || (_i> len ) ) + throw runtime_error( "xOver2: applying xOver past boundaries"); + + for ( unsigned i = _i; i < _j; i++ ) { + Type tmp = _eo.gene( i ); + _eo.gene( i ) = _eo2.gene( i ); + _eo2.gene( i ) = tmp ; + } + + } + +}; + +#endif + diff --git a/eo/src/rnd_generators.h b/eo/src/rnd_generators.h index c7beace7..5074af01 100644 --- a/eo/src/rnd_generators.h +++ b/eo/src/rnd_generators.h @@ -1,85 +1,85 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - rnd_generators.h - Some utility functors for generating random generators: - uniform_generator : generates uniform floats or doubles - random_generator : generates unsigneds, ints etc. - normal_generator : normally distributed floats or doubles - - (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ - -//----------------------------------------------------------------------------- - -#ifndef eoRND_GENERATORS_H -#define eoRND_GENERATORS_H - -#include "eoRNG.h" - -/** - The class uniform_generator can be used in the STL generate function - to easily generate random floats and doubles between [0, _max). _max - defaults to 1.0 -*/ -template class uniform_generator -{ - public : - uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {} - - virtual T operator()(void) { return (T) uniform.uniform(maxim); } - private : - T maxim; - eoRng& uniform; -}; - -/** - The class random_generator can be used in the STL generate function - to easily generate random ints between [0, _max). -*/ -template class random_generator -{ - public : - random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {} - - virtual T operator()(void) { return (T) random.random(max); } - - private : - T maxim; - eoRng& random; -}; - -/** - The class normal_generator can be used in the STL generate function - to easily generate gaussian distributed floats and doubles. The user - can supply a standard deviation which defaults to 1. -*/ -template class normal_generator -{ - public : - normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} - - virtual T operator()(void) { return (T) normal.normal(stdev); } - - private : - T stdev; - eoRng& normal; -}; - -#endif \ No newline at end of file +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + rnd_generators.h + Some utility functors for generating random generators: + uniform_generator : generates uniform floats or doubles + random_generator : generates unsigneds, ints etc. + normal_generator : normally distributed floats or doubles + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +//----------------------------------------------------------------------------- + +#ifndef eoRND_GENERATORS_H +#define eoRND_GENERATORS_H + +#include "eoRNG.h" + +/** + The class uniform_generator can be used in the STL generate function + to easily generate random floats and doubles between [0, _max). _max + defaults to 1.0 +*/ +template class uniform_generator +{ + public : + uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {} + + virtual T operator()(void) { return (T) uniform.uniform(maxim); } + private : + T maxim; + eoRng& uniform; +}; + +/** + The class random_generator can be used in the STL generate function + to easily generate random ints between [0, _max). +*/ +template class random_generator +{ + public : + random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {} + + virtual T operator()(void) { return (T) random.random(max); } + + private : + T maxim; + eoRng& random; +}; + +/** + The class normal_generator can be used in the STL generate function + to easily generate gaussian distributed floats and doubles. The user + can supply a standard deviation which defaults to 1. +*/ +template class normal_generator +{ + public : + normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} + + virtual T operator()(void) { return (T) normal.normal(stdev); } + + private : + T stdev; + eoRng& normal; +}; + +#endif diff --git a/eo/src/selectors.h b/eo/src/selectors.h index 4b0dad6d..db111a50 100644 --- a/eo/src/selectors.h +++ b/eo/src/selectors.h @@ -1,313 +1,313 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - - ----------------------------------------------------------------------------- - selectors.h - A bunch of useful selector functions. They generally have three forms: - - template - It select(It begin, It end, params, eoRng& gen = rng); - - template - const EOT& select(const eoPop& pop, params, eoRng& gen = rng); - - template - EOT& select(eoPop& pop, params, eoRng& gen = rng); - - where select is one of: roulette_wheel, deterministic_tournament - and stochastic_tournament (at the moment). - - (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ - -#ifndef SELECT__H -#define SELECT__H - -#include "eoRNG.h" -#include "eoException.h" - -template -bool minimizing_fitness() -{ - EOT eo1; // Assuming people don't do anything fancy in the default constructor! - EOT eo2; - - /* Dear user, when the two line below do not compile you are most - likely not working with scalar fitness values. In that case we're sorry - but you cannot use lottery or roulette_wheel selection... - */ - eo1.fitness(0.0); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this - eo2.fitness(1.0); - - return eo2 < eo1; // check whether we have a minimizing fitness -}; - -inline double scale_fitness(const std::pair& _minmax, double _value) -{ - if (_minmax.first == _minmax.second) - { - return 0.0; // no differences in fitness, population converged! - } - // else - - return (_value - _minmax.first) / (_minmax.second - _minmax.first); -} - -template -double sum_fitness(It begin, It end) -{ - double sum = 0.0; - - for (; begin != end; ++begin) - { - double v = static_cast(begin->fitness()); - if (v < 0.0) - throw eoNegativeFitnessException(); - sum += v; - } - - return sum; -} - -template -double sum_fitness(const eoPop& _pop) -{ - return sum_fitness(_pop.begin(), _pop.end()); -} - -template -double sum_fitness(const eoPop& _pop, std::pair& _minmax) -{ - eoPop::const_iterator it = _pop.begin(); - - _minmax.first = it->fitness(); - _minmax.second = it++->fitness(); - - for(; it != _pop.end(); ++it) - { - double v = static_cast(it->fitness()); - - _minmax.first = std::min(_minmax.first, v); - _minmax.second = std::max(_minmax.second, v); - - rawTotal += v; - } - - if (minimizing_fitness()) - { - std::swap(_minmax.first, _minmax.second); - } - - scaledTotal = 0.0; - - // unfortunately a second loop is neccessary to scale the fitness - for (it = _pop.begin(); it != _pop.end(); ++it) - { - double v = scale_fitness(static_cast(it->fitness())); - - scaledTotal += v; - } -} - -template -It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng) -{ - float roulette = _gen.uniform(total); - - It i = _begin; - - while (roulette > 0.0) - { - roulette -= static_cast(*(i++)); - } - - return --i; -} - -template -const EOT& roulette_wheel(const eoPop& _pop, double total, eoRng& _gen = rng) -{ - float roulette = _gen.uniform(total); - - eoPop::const_iterator i = _pop.begin(); - - while (roulette > 0.0) - { - roulette -= static_cast((i++)->fitness()); - } - - return *--i; -} - -template -EOT& roulette_wheel(eoPop& _pop, double total, eoRng& _gen = rng) -{ - float roulette = _gen.uniform(total); - - eoPop::iterator i = _pop.begin(); - - while (roulette > 0.0) - { - roulette -= static_cast((i++)->fitness()); - } - - return *--i; -} - -template -It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) -{ - It best = _begin + _gen.random(_end - _begin); - - for (unsigned i = 0; i < _t_size - 1; ++i) - { - It competitor = _begin + _gen.random(_end - _begin); - - if (*best < *competitor) - { - best = competitor; - } - } - - return best; -} - -template -const EOT& deterministic_tournament(const eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) -{ - return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); -} - -template -EOT& deterministic_tournament(eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) -{ - return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); -} - -template -It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) -{ - It worst = _begin + _gen.random(_end - _begin); - - for (unsigned i = 0; i < _t_size - 1; ++i) - { - It competitor = _begin + _gen.random(_end - _begin); - - if (competitor == worst) - { - --i; - continue; // try again - } - - if (*competitor < *worst) - { - worst = competitor; - } - } - - return worst; -} - -template -const EOT& inverse_deterministic_tournament(const eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) -{ - return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); -} - -template -EOT& inverse_deterministic_tournament(eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) -{ - return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); -} - -template -It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) -{ - It i1 = _begin + _gen.random(_end - _begin); - It i2 = _begin + _gen.random(_end - _begin); - - bool return_better = _gen.flip(_t_rate); - - if (*i1 < *i2) - { - if (return_better) return i2; - // else - - return i1; - } - else - { - if (return_better) return i1; - // else - } - // else - - return i2; -} - -template -const EOT& stochastic_tournament(const eoPop& _pop, double _t_rate, eoRng& _gen = rng) -{ - return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); -} - -template -EOT& stochastic_tournament(eoPop& _pop, double _t_rate, eoRng& _gen = rng) -{ - return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); -} - -template -It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) -{ - It i1 = _begin + _gen.random(_end - _begin); - It i2 = _begin + _gen.random(_end - _begin); - - bool return_worse = _gen.flip(_t_rate); - - if (*i1 < *i2) - { - if (return_worse) return i1; - // else - - return i2; - } - else - { - if (return_worse) return i2; - // else - } - // else - - return i1; -} - -template -const EOT& inverse_stochastic_tournament(const eoPop& _pop, double _t_rate, eoRng& _gen = rng) -{ - return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); -} - -template -EOT& inverse_stochastic_tournament(eoPop& _pop, double _t_rate, eoRng& _gen = rng) -{ - return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); -} - - -#endif \ No newline at end of file +/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + selectors.h + A bunch of useful selector functions. They generally have three forms: + + template + It select(It begin, It end, params, eoRng& gen = rng); + + template + const EOT& select(const eoPop& pop, params, eoRng& gen = rng); + + template + EOT& select(eoPop& pop, params, eoRng& gen = rng); + + where select is one of: roulette_wheel, deterministic_tournament + and stochastic_tournament (at the moment). + + (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ + +#ifndef SELECT__H +#define SELECT__H + +#include "eoRNG.h" +#include "eoException.h" + +template +bool minimizing_fitness() +{ + EOT eo1; // Assuming people don't do anything fancy in the default constructor! + EOT eo2; + + /* Dear user, when the two line below do not compile you are most + likely not working with scalar fitness values. In that case we're sorry + but you cannot use lottery or roulette_wheel selection... + */ + eo1.fitness(0.0); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this + eo2.fitness(1.0); + + return eo2 < eo1; // check whether we have a minimizing fitness +}; + +inline double scale_fitness(const std::pair& _minmax, double _value) +{ + if (_minmax.first == _minmax.second) + { + return 0.0; // no differences in fitness, population converged! + } + // else + + return (_value - _minmax.first) / (_minmax.second - _minmax.first); +} + +template +double sum_fitness(It begin, It end) +{ + double sum = 0.0; + + for (; begin != end; ++begin) + { + double v = static_cast(begin->fitness()); + if (v < 0.0) + throw eoNegativeFitnessException(); + sum += v; + } + + return sum; +} + +template +double sum_fitness(const eoPop& _pop) +{ + return sum_fitness(_pop.begin(), _pop.end()); +} + +template +double sum_fitness(const eoPop& _pop, std::pair& _minmax) +{ + eoPop::const_iterator it = _pop.begin(); + + _minmax.first = it->fitness(); + _minmax.second = it++->fitness(); + + for(; it != _pop.end(); ++it) + { + double v = static_cast(it->fitness()); + + _minmax.first = std::min(_minmax.first, v); + _minmax.second = std::max(_minmax.second, v); + + rawTotal += v; + } + + if (minimizing_fitness()) + { + std::swap(_minmax.first, _minmax.second); + } + + scaledTotal = 0.0; + + // unfortunately a second loop is neccessary to scale the fitness + for (it = _pop.begin(); it != _pop.end(); ++it) + { + double v = scale_fitness(static_cast(it->fitness())); + + scaledTotal += v; + } +} + +template +It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng) +{ + float roulette = _gen.uniform(total); + + It i = _begin; + + while (roulette > 0.0) + { + roulette -= static_cast(*(i++)); + } + + return --i; +} + +template +const EOT& roulette_wheel(const eoPop& _pop, double total, eoRng& _gen = rng) +{ + float roulette = _gen.uniform(total); + + eoPop::const_iterator i = _pop.begin(); + + while (roulette > 0.0) + { + roulette -= static_cast((i++)->fitness()); + } + + return *--i; +} + +template +EOT& roulette_wheel(eoPop& _pop, double total, eoRng& _gen = rng) +{ + float roulette = _gen.uniform(total); + + eoPop::iterator i = _pop.begin(); + + while (roulette > 0.0) + { + roulette -= static_cast((i++)->fitness()); + } + + return *--i; +} + +template +It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) +{ + It best = _begin + _gen.random(_end - _begin); + + for (unsigned i = 0; i < _t_size - 1; ++i) + { + It competitor = _begin + _gen.random(_end - _begin); + + if (*best < *competitor) + { + best = competitor; + } + } + + return best; +} + +template +const EOT& deterministic_tournament(const eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) +{ + return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); +} + +template +EOT& deterministic_tournament(eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) +{ + return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); +} + +template +It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) +{ + It worst = _begin + _gen.random(_end - _begin); + + for (unsigned i = 0; i < _t_size - 1; ++i) + { + It competitor = _begin + _gen.random(_end - _begin); + + if (competitor == worst) + { + --i; + continue; // try again + } + + if (*competitor < *worst) + { + worst = competitor; + } + } + + return worst; +} + +template +const EOT& inverse_deterministic_tournament(const eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) +{ + return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); +} + +template +EOT& inverse_deterministic_tournament(eoPop& _pop, unsigned _t_size, eoRng& _gen = rng) +{ + return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); +} + +template +It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) +{ + It i1 = _begin + _gen.random(_end - _begin); + It i2 = _begin + _gen.random(_end - _begin); + + bool return_better = _gen.flip(_t_rate); + + if (*i1 < *i2) + { + if (return_better) return i2; + // else + + return i1; + } + else + { + if (return_better) return i1; + // else + } + // else + + return i2; +} + +template +const EOT& stochastic_tournament(const eoPop& _pop, double _t_rate, eoRng& _gen = rng) +{ + return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); +} + +template +EOT& stochastic_tournament(eoPop& _pop, double _t_rate, eoRng& _gen = rng) +{ + return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); +} + +template +It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) +{ + It i1 = _begin + _gen.random(_end - _begin); + It i2 = _begin + _gen.random(_end - _begin); + + bool return_worse = _gen.flip(_t_rate); + + if (*i1 < *i2) + { + if (return_worse) return i1; + // else + + return i2; + } + else + { + if (return_worse) return i2; + // else + } + // else + + return i1; +} + +template +const EOT& inverse_stochastic_tournament(const eoPop& _pop, double _t_rate, eoRng& _gen = rng) +{ + return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); +} + +template +EOT& inverse_stochastic_tournament(eoPop& _pop, double _t_rate, eoRng& _gen = rng) +{ + return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); +} + + +#endif